How to Enable Query Caching in WordPress

How to Enable Query Caching in WordPress

Enabling query caching in WordPress can drastically improve your site’s speed and reduce server load by storing database query results in memory. This prevents repeated queries and ensures faster page loads. Here’s a quick guide to get started:

  • Why It Matters: Query caching reduces database strain and speeds up load times, especially for dynamic pages like e-commerce checkouts or dashboards.
  • Tools You Need: Redis or Memcached for persistent caching, along with plugins like Redis Object Cache or W3 Total Cache.
  • Setup Steps:
    1. Install Redis or Memcached: Use your server’s package manager to install and configure.
    2. Activate a WordPress Plugin: Enable object caching through plugins designed for Redis or Memcached integration.
    3. Test Performance: Use tools like Query Monitor to verify cache effectiveness and measure improvements.

Pro Tip: Persistent caching is critical for high-traffic sites. Ensure your hosting supports Redis or Memcached, and configure them properly to handle your site’s load.

Ready to make your WordPress site faster? Let’s dive into the details!

How To Setup Redis Object Caching For WordPress On Cloudways 2020 – WordPress Redis Cache Tutorial

Redis

What is Query Caching in WordPress

Query caching, often called object caching, is a method of storing database query results in your server’s RAM. Instead of running the same queries repeatedly, WordPress checks the cache first and delivers the stored data instantly. This reduces the load on the MySQL database and helps avoid performance bottlenecks. Essentially, this caching layer acts as a middleman between your PHP code and the MySQL database. Normally, when a visitor loads a page, WordPress runs several queries to retrieve posts, user information, settings, and more. Query caching streamlines this process by distinguishing between "cache hits" and "cache misses", which we’ll explain further.

How Query Caching Works

When a "cache hit" occurs, the requested data is retrieved immediately from the cache. On the other hand, a "cache miss" means the data isn’t in the cache, prompting WordPress to query the database, store the result in the cache, and then serve it.

WordPress comes with a built-in object cache, but it’s non-persistent, meaning it only works for the duration of a single page load. To make caching effective across multiple requests and users, you’ll need a persistent caching solution like Redis or Memcached. These tools store cached data in memory, making it accessible for future page loads.

For example, in June 2019, Senior Developer Ashley Rich tested a WordPress 5.2.2 installation with WooCommerce 3.6.4. By using persistent object caching, the number of queries on the cart page dropped from 32 to just 2, and the page generation time decreased from 0.085 seconds to 0.053 seconds [4].

Why Query Caching Matters

Query caching plays a crucial role in improving page load times and reducing server strain. This is especially important for dynamic pages that can’t rely on full-page caching, such as e-commerce checkouts, membership dashboards, or the WordPress admin area. Since these pages need to be generated fresh for each user, object caching ensures they remain fast and efficient without overloading the database.

The performance improvements are impressive. Implementing query caching can cut overall server load by as much as 80% [5]. Sites that use object caching effectively often see load times of 200–500ms for cached content, compared to 1,000–3,000ms without caching [7]. High-traffic websites should aim for a cache hit rate of 70% or more to maintain peak performance [7].

Beyond speeding up page loads, query caching also enhances Time to First Byte (TTFB) by reducing the time it takes to process and send a response [5]. Understanding these benefits lays the groundwork for implementing caching strategies effectively, which we’ll cover in the next steps.

What You Need Before Starting

Before diving into query caching, it’s essential to check your hosting setup and pinpoint any slow queries. If you’re on entry-level shared hosting, persistent caching might not be an option. Instead, consider using a VPS, dedicated server, or premium managed WordPress hosting for better support [2][10]. Make sure your server is running PHP 8.0 or higher, with PHP-FPM and Opcache enabled to boost performance [9].

For more advanced caching, your server needs enough RAM to prevent key eviction. High-traffic websites typically require at least 4vCPU/4GB RAM, while servers with control panels like cPanel may need 8vCPU/8GB RAM [9]. Redis should be configured with a minimum of 256MB RAM and set to the allkeys-lru eviction policy [9]. These steps help ensure your caching system runs smoothly and efficiently.

Check if Your Host Supports Caching

Many managed hosting providers include Redis or Memcached support, often with simple activation options in their control panels. For instance, Hostinger‘s hPanel shows this directly in the interface, while Elementor Hosting offers one-click activation starting at $8.99/month [2][10]. In some cases, you might need to enable caching manually through "PHP Options" or "Extensions" [10][13].

If you’re unsure, reach out to your host and ask: "Do you support Redis or Memcached? How can I enable it for my site?" [2]. For those comfortable with command-line tools, running wp cache status via WP-CLI can also confirm your current cache setup [2].

Tools to Find Slow Queries

To identify slow queries, start with Query Monitor, a free tool that lists all database queries for each page load [6][12]. Its "Queries by Component" panel highlights which plugins or themes are responsible for the most resource-intensive requests. This can help you decide whether to cache a specific query or replace a problematic plugin [6]. If you see "External object cache not in use" in Query Monitor’s Overview panel, it means persistent caching isn’t active yet [6].

Another useful tool is Debug Bar, which provides a stack trace before a WP_Query call [8]. For more detailed insights, advanced users can try New Relic for enterprise-level monitoring of query execution times [11]. Additionally, you can enable WordPress’s built-in debugging by adding define( 'SAVEQUERIES', true ); to your wp-config.php file. However, be cautious – this feature adds significant overhead and should only be used during active debugging [11].

How to Enable Query Caching in WordPress

WordPress Query Caching Setup Guide: 3-Step Implementation Process

WordPress Query Caching Setup Guide: 3-Step Implementation Process

To enable query caching in WordPress, you’ll need to use a persistent caching backend like Redis or Memcached. These tools are widely supported by hosting providers, making them relatively simple to set up. They work by reducing database queries, which can significantly improve your site’s performance. Below, we’ll walk you through setting up Redis, Memcached, or custom caching, depending on your needs and technical setup.

Setting Up Redis for Object Caching

Redis is a popular choice for object caching. To get started, you’ll need both the Redis server and a PHP Redis extension (such as phpredis or predis). Many managed hosting providers offer Redis as a one-click install option. If you’re using a self-managed VPS or dedicated server, you’ll likely need to install it manually via SSH.

For Ubuntu or Debian systems, you can install Redis with these commands:

sudo apt install redis-server sudo apt install php-redis 

Once installed, it’s important to secure your Redis setup. Edit the configuration file (usually located at /etc/redis/redis.conf) to add a password using the requirepass directive. Additionally, set the maxmemory to at least 256MB and configure the maxmemory-policy to allkeys-lru, which ensures frequently accessed data stays in the cache.

After the server-side setup, activate the Redis Object Cache plugin in WordPress. Before doing so, delete any existing /wp-content/object-cache.php file from prior caching plugins and flush the Redis database to prevent stale data:

redis-cli flushall 

Then, navigate to Settings > Redis in your WordPress dashboard and click Enable Object Cache. This will deploy the required drop-in file to your /wp-content/ folder.

As Steve Bonisteel, Technical Editor at Kinsta, notes: "Redis can act as a buffer between your visitors and your database… serving cached data from memory." [14]

Configuration Setting Recommended Value Purpose
maxmemory 256MB Limits Redis memory usage
maxmemory-policy allkeys-lru Keeps frequently accessed data cached
appendonly yes Ensures data persistence to disk

Setting Up Memcached for Object Caching

Memcached

Memcached is another robust option for object caching. To use it, you’ll need to install both the Memcached server and a compatible PHP extension (either memcache or memcached). For Ubuntu or Debian, use the following commands:

sudo apt-get update sudo apt install memcached php-memcached 

On CentOS, you can install it with:

yum install memcached 

After installation, secure Memcached by editing its configuration file (found at /etc/sysconfig/memcached.conf or /etc/memcached.conf). Restrict access to the local server by setting the OPTIONS line to:

-l 127.0.0.1 -U 0 

Then restart the service:

systemctl restart memcached 

To integrate Memcached with WordPress, you can choose one of two methods:

  • Plugin Method: Install a caching plugin like W3 Total Cache, then enable both Database Cache and Object Cache. Select Memcached as the caching method in the plugin settings.
  • Manual Drop-in Method: Download the object-cache.php file from a trusted source (e.g., the official GitHub repository) and place it in your /wp-content/ folder. For additional security, define a unique salt in your wp-config.php file:
    define('WP_CACHE_KEY_SALT', 'your_unique_salt_here'); 

    If you’re using a non-standard server setup, specify your server details like this:

    $memcached_servers = array('default' => array('127.0.0.1:11211')); 

Adding Custom Query Caching with WP_Object_Cache

For developers who want more control, custom query caching is a great option. Using the WP_Object_Cache API, you can selectively cache specific queries instead of enabling site-wide caching. This method is particularly useful if you’ve identified slow queries with tools like Query Monitor.

The process involves checking if the data is already cached before running a database query. If the data exists (a cache hit), it is served from memory. If not (a cache miss), the query runs and the result is stored for future use.

Here’s an example of caching a custom WP_Query:

  1. Generate a unique cache key:
    $key = 'custom_query_' . md5(serialize($args)); 
  2. Check the cache and store the result if it’s not already cached:
    if ( false === ( $query_results = wp_cache_get( $key ) ) ) {     $query_results = new WP_Query( $args );     wp_cache_set( $key, $query_results, 'my_cache_group', 3600 ); } 

    In this example, the results are cached for one hour (3600 seconds).

It’s important to note that WordPress’s default object caching is non-persistent, meaning the cache only lasts for a single page load. To make it persistent across requests, you’ll need to use a backend like Redis or Memcached.

Test and Verify Query Caching

Once you’ve set up query caching, it’s crucial to verify that everything is working as expected. A helpful tool for this is Query Monitor, a free plugin that provides insights into what’s happening behind the scenes on your WordPress site.

Check Caching with Query Monitor

Query Monitor

Query Monitor acts as a diagnostic tool for WordPress. After you install it, head to the Overview panel in your WordPress admin toolbar. The key metric to watch is the Object Cache hit rate – this shows the percentage of requests being served from the cache instead of hitting the database. Ideally, this rate should exceed 90%, indicating that caching is functioning effectively [12].

If you see a message like "External object cache not in use", it means your persistent cache isn’t active [6]. Additionally, check the Total number of SQL queries displayed in the admin toolbar. After enabling caching, you should notice a significant drop in this number [6].

For more detailed insights, review the Object Cache panel. Pay attention to the number of Slow-Ops, which are cache operations taking longer than 5ms. A high count here could point to latency issues [12].

Once you’ve confirmed that your cache metrics are in good shape, the next step is to assess how caching impacts your overall site performance.

Measure Performance Changes

To understand the benefits of caching, compare your site’s performance before and after enabling it. In March 2021, developer Ashley Rich reported a dramatic improvement – reducing queries from 32 to just 2 and cutting page generation time from 0.085 seconds to 0.053 seconds [4].

You can measure your own site’s improvements using tools like GTmetrix or Pingdom. Pay special attention to the Time to First Byte (TTFB), which should decrease noticeably once caching is active [15]. For more detailed tests, use tools like ApacheBench to analyze request rates and average response times [4].

When conducting these tests, temporarily disable full-page caching to isolate the effects of query caching on database load and PHP execution [15]. Also, make sure to test as a logged-out user, since cached results can vary depending on user roles and permissions [15][16].

Query Monitor Metric What It Means What to Look For
Object Cache Hit Rate Percentage of requests served from cache Aim for 90% or higher [12]
Total SQL Queries Number of database requests per page Should drop significantly after caching [6]
Slow-Ops Cache operations taking over 5ms Lower numbers indicate better performance [12]
Page Generation Time Total time to render the page Should decrease with reduced SQL time [6][4]

Troubleshooting Query Caching Problems

Even with a proper setup, query caching can run into hiccups like stale data, misconfigurations, or hosting constraints. Below are common issues you might encounter and practical steps to resolve them.

Clear Cache After Content Updates

WordPress usually clears the cache during actions like updating posts or adding comments [1]. However, if updates aren’t showing up, you may need to manually flush the cache. The quickest way is to use the wp_cache_flush() function in your code or click the "Flush Cache" button in your caching plugin [2].

If you prefer using the command line, run this WP-CLI command to clear the persistent object cache:

wp cache flush 

Important: Only flush the cache as part of troubleshooting [2].

Prevent Caching Dynamic Content

Caching dynamic pages, such as WooCommerce cart or checkout pages, can lead to outdated data being displayed [4]. To avoid this, configure your caching tool to exclude these specific URLs or bypass caching when certain cookies are detected. In these cases, object caching works better since it stores individual query results rather than caching the entire page output [4].

If dynamic content isn’t the root of the issue, check your hosting environment’s caching support to rule out other problems.

Confirm Your Host Supports Persistent Caching

For persistent caching to work, your host must support Redis or Memcached [2]. You can verify this using the Object Cache panel in Query Monitor. If it displays "Persistent Cache: true," you’re good to go. If it says "External object cache not in use," reach out to your hosting provider to make sure Redis or Memcached is enabled.

Another potential issue is encountering 502 errors after enabling object caching. This often happens when the wp_options table contains too much autoloaded data. For example, hosting platforms like WP Engine limit the object cache buffer to 1MB, and keeping autoloaded data under 800,000 bytes is essential to avoid crashes [17]. If you hit a 502 error, review the wp_options table and reduce any data marked as autoload = "yes" [17].

These troubleshooting steps can help maintain an efficient query caching setup, ensuring your WordPress site performs at its best.

Issue Common Cause Recommended Solution
502 Bad Gateway Autoloaded data exceeds cache buffer (1MB) Reduce wp_options size or temporarily disable object cache [17]
Changes Not Visible Stale cache or multiple caching layers Flush the object cache and clear CDN/browser caches [18][2]
Personalized Data Leak Caching dynamic/logged-in content Exclude dynamic pages or use "bypass on cookie" rules [4]
Slow Admin Dashboard Lack of persistent object caching Enable Redis or Memcached on the server [2]

Conclusion

Enabling query caching in WordPress can significantly boost your site’s performance by easing the load on your database and speeding up page generation. The process involves a few key steps: identifying slow queries using tools like Query Monitor, setting up persistent object caching with options like Redis or Memcached, and testing your configuration to ensure the cache is functioning properly. When done right, query caching can cut server resource usage by as much as 80% and improve page load times by 2 to 5 times [5][19].

The benefits of object caching are well-documented. Tests consistently show that it reduces database queries and speeds up load times, which directly improves the user experience and helps lower bounce rates. However, for these gains to be fully realized, your hosting provider must support persistent caching backends like Redis or Memcached. Without this support, the advantages will be limited [3][6]. To verify that your setup is working, check the Object Cache panel in Query Monitor – look for "Persistent Cache: true." For the best results, combine query caching with efficient cache management and avoid using overlapping caching plugins. Following these steps will help you maintain a fast and reliable WordPress site.

FAQs

What’s the difference between Redis and Memcached for query caching in WordPress?

Redis and Memcached are both excellent in-memory caching tools that can enhance WordPress performance, but they differ in what they bring to the table. Redis stands out with its support for complex data structures like strings, hashes, lists, and sets, along with the option for persistence to disk. This makes it a strong choice when you need more advanced caching or want to ensure data durability. Memcached, by contrast, is a straightforward and lightweight key-value store, perfect for simpler caching tasks without the need for persistence.

When it comes to speed, both deliver incredibly fast sub-millisecond performance. Memcached often shines in basic get/set operations due to its simplicity, while Redis may introduce a bit more overhead because of its broader feature set. For scalability, Memcached is easier to scale horizontally by adding more nodes, whereas Redis supports clustering but involves more configuration. Ultimately, the choice depends on your requirements – Redis is ideal for more advanced scenarios, while Memcached is better suited for straightforward, high-speed caching needs.

How can I check if query caching is working properly on my WordPress site?

To ensure query caching is working properly, tools like the Query Monitor plugin or a caching plugin’s built-in diagnostics (such as WP Rocket) can be incredibly helpful. These tools give you a clear view of how your database queries are managed.

Begin by installing and activating the Query Monitor plugin directly from your WordPress dashboard. Once activated, you’ll find it in the admin toolbar, where you can check important metrics such as:

  • Object Cache Hit Rate: A higher percentage indicates that more queries are being served from the cache.
  • Number of Database Queries: Fewer queries mean less strain on your database.
  • Page Generation Time: Faster times point to better overall performance.

To dive deeper, compare these metrics before and after enabling query caching. Test different pages across your site to make sure the improvements are consistent. Keep an eye on these metrics regularly, especially after updates or installing new plugins, to ensure that your caching setup continues to deliver optimal results.

What can I do if my hosting provider doesn’t support Redis or Memcached?

If your hosting provider doesn’t offer Redis or Memcached support, don’t worry – there are still ways to boost your WordPress site’s performance through query caching:

  • Upgrade your hosting: Moving to a host that includes built-in object caching, like Redis or Memcached, can make a big difference in performance. It’s worth considering if speed is a priority.
  • Install a caching plugin: Reliable plugins like W3 Total Cache or LiteSpeed Cache can help by storing pre-rendered pages, significantly reducing the load on your database.
  • Tidy up your database: Minimize query load by keeping your database lean. This can involve limiting post revisions, adding proper indexing, and deactivating plugins you don’t actually use.

For additional tools and expert advice, check out WP Winners – they provide curated resources to help you fine-tune your WordPress site.

Related Blog Posts


Discover more from WP Winners 🏆

Subscribe to get the latest posts sent to your email.

More WorDPRESS Tips, tutorials and Guides

Discover more from WP Winners 🏆

Subscribe now to keep reading and get access to the full archive.

Continue reading