WPBeginner

Beginner's Guide for WordPress

  • Blog
    • Beginners Guide
    • News
    • Opinion
    • Showcase
    • Themes
    • Tutorials
    • WordPress Plugins
  • Start Here
    • How to Start a Blog
    • Create a Website
    • Start an Online Store
    • Best Website Builder
    • Email Marketing
    • WordPress Hosting
    • Business Name Ideas
  • Deals
    • Bluehost Coupon
    • SiteGround Coupon
    • WP Engine Coupon
    • HostGator Coupon
    • Domain.com Coupon
    • Constant Contact
    • View All Deals »
  • Glossary
  • Videos
  • Products
X
☰
Beginner's Guide for WordPress / Start your WordPress Blog in minutes
Choosing the Best
WordPress Hosting
How to Easily
Install WordPress
Recommended
WordPress Plugins
View all Guides

WPBeginner» Blog» Tutorials» Speed Up Your WordPress by Caching Custom Queries using Transients API

Speed Up Your WordPress by Caching Custom Queries using Transients API

Last updated on March 8th, 2012 by Editorial Staff
28 Shares
Share
Tweet
Share
Pin
Free WordPress Video Tutorials on YouTube by WPBeginner
Speed Up Your WordPress by Caching Custom Queries using Transients API

O boy, the title sounds scary doesn’t it. You have nothing to worry because we will break it all down. Is your theme running custom WordPress queries to show random posts, popular posts, recent posts etc in the sidebar or anywhere else? If yes, then you should consider using the WordPress transient API to cache these queries to reduce resource consumption as well as helping the load time. In this article, we will show you how to speed up your WordPress site by caching custom queries using the Transients API.

Note: You need to understand how WordPress themes work (loops etc), in order for you to follow this post.

So this whole caching and transient lingo is going over my head. Well don’t worry let us explain what it does. Basically if you are running a site like List25 and have a loop that shows 6 random posts in your sidebar, then transient API can help. Every time a user refreshes the page, that custom WP Query that you have will go in your database and pull 6 posts at random. If you are a relatively new site, it shouldn’t be that bad. But if you are getting A LOT of people to your site, then it can crash your SQL server, and you will see the “Error Establishing Database Connection” screen. By adding a few extra lines of code, you can easily store the results of that query (cache it) for a certain period of time using the Transients API.

Example of the loop code that we had for pulling random posts:

<?php $random_query = new WP_Query('orderby=rand&posts_per_page=6');
while ($random_query->have_posts()) : $random_query->the_post();
?>
<div class="gridcontainer">
<div class="gridthumb"><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_post_thumbnail(); ?></a></div>
<div class="gridcontent">
<div class="gridtext"><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></div>
</div>
</div>
<?php endwhile; ?>

The coolest part about our random posts query in the sidebar was it showed new content every time. So by caching the query for 12 hours, we will have the same 6 posts showing for 12 hours right? Well, we found a work around thanks to the suggestion of our friend Konstantin Kovshenin (@kovshenin). He suggested that instead of using WP_Query, we use get_posts and pull 20 posts instead. Cache the results of that query using the transients API, and then use the array_rand() function to show only 6 posts out of the original 20 at random. This way we can keep simulate the random effect on the site.

First thing we did was set the transient. We got the code from the WordPress Codex page.

// Get any existing copy of our transient data
if ( false === ( $special_query_results = get_transient( 'special_query_results' ) ) ) {
    // It wasn't there, so regenerate the data and save the transient
	$randargs = array('orderby' => 'rand', 'numberposts' => 20);
	$special_query_results = get_posts($randargs);
    set_transient( 'special_query_results', $special_query_results, 60*60*12 );
}

Notice the 60*60*12 is the area where you can control the length of the cache. Feel free to change it to whatever you like. Now if we show the $special_query_results using the foreach loop, we will have all 20 posts displayed. So we need to utilize the array_rand() function to only pull 6 items at random. We added the code like this:

$randomposts = get_transient( 'special_query_results' );
$randkey = array_rand( $randomposts, 6 );

Now this will pull out 6 post IDs at random from our transient data. However, it will not pull the values for each post. So we had to do add this bits of code:

$sixposts[0] = $randomposts[$randkey[0]];
$sixposts[1] = $randomposts[$randkey[1]];
$sixposts[2] = $randomposts[$randkey[2]];
$sixposts[3] = $randomposts[$randkey[3]];
$sixposts[4] = $randomposts[$randkey[4]];
$sixposts[5] = $randomposts[$randkey[5]];

Basically we created an array for $sixposts in which we assign a value to each of those items. Not sure if this was the best way of going about it, but it worked. If any of you have better suggestions, then feel free to post it in the comments.

After doing that, we are now ready to display the loop. Simply put the code like this:

global $post; //required for it to work
foreach( $sixposts as $post ) :  setup_postdata($post);

//All the items go here.

endforeach; 

setup_postdata allows you to use all loop tags inside this foreach loop such as the_permalink etc.

To make it easy for everyone, here is the final code that we have:

<?php
// Get any existing copy of our transient data
if ( false === ( $special_query_results = get_transient( 'special_query_results' ) ) ) {
    // It wasn't there, so regenerate the data and save the transient
	$randargs = array('orderby' => 'rand', 'numberposts' => 20);
	$special_query_results = get_posts($randargs);
    set_transient( 'special_query_results', $special_query_results, 60*60*12 );
}

// Use the data like you would have normally...
$randomposts = get_transient( 'special_query_results' );
$randkey = array_rand( $randomposts, 6 );
$sixposts[0] = $randomposts[$randkey[0]];
$sixposts[1] = $randomposts[$randkey[1]];
$sixposts[2] = $randomposts[$randkey[2]];
$sixposts[3] = $randomposts[$randkey[3]];
$sixposts[4] = $randomposts[$randkey[4]];
$sixposts[5] = $randomposts[$randkey[5]];

global $post;
foreach( $sixposts as $post ) :  setup_postdata($post); ?>

<div class="gridcontainer">
<div class="gridthumb"><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_post_thumbnail(); ?></a></div>
<div class="gridcontent">
<div class="gridtext"><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></div>
</div>
</div>

<?php endforeach; ?>

Ta da, now you are only making this DB query once every 12 hours no matter how many users are visiting your site.

28 Shares
Share
Tweet
Share
Pin
Popular on WPBeginner Right Now!
  • Google Analytics in WordPress

    How to Install Google Analytics in WordPress for Beginners

  • Revealed: Why Building an Email List is so Important Today (6 Reasons)

    Revealed: Why Building an Email List is so Important Today (6 Reasons)

  • How to Start Your Own Podcast (Step by Step)

    How to Start Your Own Podcast (Step by Step)

  • How to Fix the Error Establishing a Database Connection in WordPress

    How to Fix the Error Establishing a Database Connection in WordPress

About the Editorial Staff

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi. Trusted by over 1.3 million readers worldwide.

The Ultimate WordPress Toolkit

16 Comments

Leave a Reply
  1. Mato says:
    Dec 7, 2020 at 4:59 pm

    Is there a way to exclude one category from this query?

    Reply
    • WPBeginner Support says:
      Dec 8, 2020 at 9:48 am

      While there can be, we have not explored it at the moment

      Reply
  2. Kevious says:
    Oct 2, 2017 at 1:01 am

    Where are you adding these codes? index, header, footer, functions…etc?

    Reply
  3. javad says:
    Apr 22, 2017 at 1:44 pm

    Thank you for this article.how can i display 9 last posts of 20 posts by specific category?!

    Reply
  4. Mayank Rajput says:
    Oct 13, 2016 at 7:22 pm

    Hi,

    i have tried Transients API on post id, i have used it store same post id but when i use to reload the same page it does not return the result and if condition is true, so again it store the same value, i have tried it again and again but fails.

    Reply
  5. Cory says:
    Sep 30, 2015 at 2:15 am

    I added a date filter to the args, but strangely all of the posts group around the same dates, which doesn’t seem all that random. Without the date filter, all of the posts that displayed were from the very start of my site (3 years ago), and with the date filter, filtering the last 90 days, it shows mostly posts from the last month all grouped close to each other.

    Reply
  6. Smartik says:
    May 21, 2014 at 6:34 pm

    You could do this.

    for ($i = 0; $i < 6; $i++) {
    $sixposts[$i] = $randomposts[$randkey[$i]];
    }

    Imagine if you would need 30posts instead of 6. All what you have to do is to change just one number.

    Reply
  7. Shasi kanth says:
    Feb 12, 2014 at 6:39 am

    Thanks for sharing this article. Very useful for custom optimization of database queries inside WordPress.

    Reply
  8. Luyen says:
    Nov 19, 2013 at 6:42 pm

    Super cool – i’ve always wondered about the transient API, i will definitely use it for future queries.

    Reply
  9. Jean Galea says:
    Sep 22, 2012 at 5:34 am

    I still don’t get why get_posts was used instead of WP_Query, could you expand on that?

    Reply
    • Editorial Staff says:
      Sep 22, 2012 at 7:36 am

      By using get_posts, we were able to pull 20 random posts from the database and cache the query. Then using the foreach loop, we were able to randomly display 6 out of the 20 posts. Using wp_query, you would have to pull a specific number of posts and display a same number as well.

      Reply
  10. MichealKennedy says:
    Apr 12, 2012 at 7:00 am

    Without this, my Random page generates between 45-49 queries; but with this, it jumps to 56-68 queries. 

    Reply
  11. MichealKennedy says:
    Mar 25, 2012 at 9:45 pm

    Man, every plugin should use Transients API! Does WP core make use of this? It should! And have an admin options page built into core to set up cache length and which items to cache, etc. 

    Reply
  12. Vayu says:
    Mar 21, 2012 at 3:11 am

    Interesting article, thanks for sharing!
    Why would it be better to use get_post() here rather than WP_Query()?  Just curious that’s all.
    Vayu

    Reply
    • wpbeginner says:
      Mar 23, 2012 at 6:58 am

      Its not better in general. It was better for our case. We are trying to pull 20 posts with get_posts… and then displaying 6 at random. With WP_Query, you will end up displaying all 20.

      Reply
  13. MuhammadWaqas says:
    Mar 15, 2012 at 6:49 pm

    lol. this is crazy. a little complex but I will try

    Reply

Leave a Reply Cancel reply

Thanks for choosing to leave a comment. Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published. Please Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

Over 1,320,000+ Readers

Get fresh content from WPBeginner

Featured WordPress Plugin
WPForms Logo
WPForms
Drag & Drop WordPress Form Builder Plugin. Learn More »
How to Start a Blog How to Start a Blog
I need help with ...
Starting a
Blog
WordPress
Performance
WordPress
Security
WordPress
SEO
WordPress
Errors
Building an
Online Store
Useful WordPress Guides
    • 7 Best WordPress Backup Plugins Compared (Pros and Cons)
    • How to Fix the Error Establishing a Database Connection in WordPress
    • Why You Need a CDN for your WordPress Blog? [Infographic]
    • 30 Legit Ways to Make Money Online Blogging with WordPress
    • Self Hosted WordPress.org vs. Free WordPress.com [Infograph]
    • Free Recording: WordPress Workshop for Beginners
    • 24 Must Have WordPress Plugins for Business Websites
    • How to Properly Move Your Blog from WordPress.com to WordPress.org
    • 5 Best Contact Form Plugins for WordPress Compared
    • Which is the Best WordPress Popup Plugin? (Comparison)
    • Best WooCommerce Hosting in 2021 (Comparison)
    • How to Fix the Internal Server Error in WordPress
    • How to Install WordPress - Complete WordPress Installation Tutorial
    • Why You Should Start Building an Email List Right Away
    • How to Properly Move WordPress to a New Domain Without Losing SEO
    • How to Choose the Best WordPress Hosting for Your Website
    • How to Choose the Best Blogging Platform (Comparison)
    • WordPress Tutorials - 200+ Step by Step WordPress Tutorials
    • 5 Best WordPress Ecommerce Plugins Compared
    • 5 Best WordPress Membership Plugins (Compared)
    • 7 Best Email Marketing Services for Small Business (2021)
    • How to Choose the Best Domain Registrar (Compared)
    • The Truth About Shared WordPress Web Hosting
    • When Do You Really Need Managed WordPress Hosting?
    • 5 Best Drag and Drop WordPress Page Builders Compared
    • How to Switch from Blogger to WordPress without Losing Google Rankings
    • How to Properly Switch From Wix to WordPress (Step by Step)
    • How to Properly Move from Weebly to WordPress (Step by Step)
    • Do You Really Need a VPS? Best WordPress VPS Hosting Compared
    • How to Properly Move from Squarespace to WordPress
    • How to Register a Domain Name (+ tip to get it for FREE)
    • HostGator Review - An Honest Look at Speed & Uptime (2021)
    • SiteGround Reviews from 4464 Users & Our Experts (2021)
    • Bluehost Review from Real Users + Performance Stats (2021)
    • How Much Does It Really Cost to Build a WordPress Website?
    • How to Create an Email Newsletter the RIGHT WAY (Step by Step)
    • Free Business Name Generator (A.I Powered)
    • How to Create a Free Business Email Address in 5 Minutes (Step by Step)
    • How to Install Google Analytics in WordPress for Beginners
    • How to Move WordPress to a New Host or Server With No Downtime
    • Why is WordPress Free? What are the Costs? What is the Catch?
    • How to Make a Website in 2021 – Step by Step Guide
Deals & Coupons (view all)
Envira Gallery
Envira Gallery Coupon
Get 10% off Envira Gallery, the best responsive WordPress gallery plugin available in the market.
ThirstyAffiliates
ThirstyAffiliates Coupon
Get 15% OFF on ThirstyAffiliates WordPress affiliate link management plugin.
Featured In
About WPBeginner®

WPBeginner is a free WordPress resource site for Beginners. WPBeginner was founded in July 2009 by Syed Balkhi. The main goal of this site is to provide quality tips, tricks, hacks, and other WordPress resources that allows WordPress beginners to improve their site(s).

Join our team: We are Hiring!

Site Links
  • About Us
  • Contact Us
  • FTC Disclosure
  • Privacy Policy
  • Terms of Service
  • Free Blog Setup
  • Free Business Tools
  • Growth Fund
Our Sites
  • OptinMonster
  • MonsterInsights
  • WPForms
  • SeedProd
  • Nameboy
  • RafflePress
  • Smash Balloon
  • AIOSEO

Copyright © 2009 - 2021 WPBeginner LLC. All Rights Reserved. WPBeginner® is a registered trademark.

Managed by Awesome Motive | WordPress hosting by SiteGround | WordPress Security by Sucuri.