Knowledge Base

Modifying Cache Times in BatCache

Category: Tutorials | Last modified: February 3, 2021

By default, Batcache, our page caching mechanism, will cache pages for five minutes, if the pages get at least two visits in two minutes. This might be OK for a site that gets a lot of traffic, but could be an issue for a site that does not get a lot of traffic. How can your site take advantage of page caching if it is not highly trafficked and is mostly static?

The answer is to modify the variable settings of the Batcache class.

Let’s imagine that your Pressable site is static. You have a homepage about your company, as well as a few pages about your company and contact information. Furthermore, you want these pages to load from cache, despite your site not receiving a lot of traffic. In this case, you could insert the following code at the very end of your wp-config.php file:

// Custom Batcache settings for the end of wp-config.php
global $batcache;
if ( is_object($batcache) ) {
     $batcache->max_age = 3600;  // Seconds the cached render of a page will be stored
     $batcache->seconds = 3600;  // The amount of time at least 2 people are required to visit your page for a cached render to be stored.
// End custom Batcache settings

First, the above makes sure Batcache is being used.

Secondly, we change the $batcache class variables for max_age and seconds from 300 and 120 seconds to 3600 and 3600, respectively. In the case of max_age, this tells Batcache to hold onto a page for 1 hour, rather than the default 300 seconds. For seconds, it tells Batcache to cache the page if the page gets at least two page views in the period of one hour, rather than two minutes.*

Finally, after adding the code modification above – feel free to adjust the times to your preferences – your site should load faster and more efficiently for more of your site’s visitors.

To learn more about Batcache, please see this article.

*The data is stored in memory via Memcache. As the data is stored in memory, this means that it can be removed at any time. Therefore, it is possible that the data would need to be restored in memory, despite the expiration time you have set. See this documentation for further reading. 

An Automattic Invention A family of WordPress solutions.