Improve WP_Query performance if using external object cache

Jonny Harris avatar
  • Are you using an external object cache, like Memcache or Redis? Is so, there is a little one line piece of code that can improve the performance of WP_Query and performance in general on your site.

    add_filter( 'split_the_query', 'wp_using_ext_object_cache' );

    Why does this improve performance? See these lines in WordPress core. The filter split_the_query determinants if the database query in WP_Query should get posts by ID or load the whole post object. If the post is loaded by ID, it loads the whole post object by checking the cache and is not in the cache, calling _prime_post_caches. In the case of site using an external object cache, the query should always just load the IDs, as the post object will 99.999% of the time, be in object cache already. This filter forces posts to be loaded from object cache and makes the database query simplier ( by only loading the ID). This filter is place for backwards compatibility reasons so it safe to use if you know what you are doing, but I don’t see many people using it. The above line can be put anywhere in your code, but I would recommend adding to to a mu-plugin.

Leave a Reply