I have a website with over 100,000 posts. On a term taxonomy page, the main query WP_Query->get_posts() is the slowest. I want to cache the results of this query using transients-api. I tried hooking into pre_get_posts using the following code:

  if ( !$query->is_main_query() ) return $query;
  $key = md5( serialize( $query ) );
  $transient = get_transient($key);
  if ( $transient ) return $transient;

 $query_result = new WP_Query( $query );


return  $query_result;

The above code is not working. How to achieve this?

1 Answer 1


pre_get_posts is used to modify the query arguments before the query is run. The $query is passed in by reference, so any changes you make in your function will be reflected in the query that's actually run. The return that you're doing will be ignored.

I think you might be making your problem worse here: you're running the query, putting the results into a transient with an hour's lifetime, then returning a value that will not be used. Then the query runs again once your action is done.

  • Thanks. How to achieve transient-api caching for such queries then?
    – dc09
    May 14, 2023 at 17:12
  • It seems the primary advice given is "Install a caching plugin": Optimization—Caching.
    – Pat J
    May 14, 2023 at 17:19
  • Caching is already enabled on the website. As per the question, I need a way to cache db query results.
    – dc09
    May 14, 2023 at 17:25
  • Looking at the core code used to fetch posts, it appears WordPress already does a lot of caching when it's grabbing posts, using its built-in object cache. (I seem to recall that the object cache uses transients or—if it's available—a service like Redis, but I can't find the reference.) Are you using core functions like get_posts() or is there a custom function to gather the relevant posts? If the latter, please edit your question to show us what you're trying.
    – Pat J
    May 17, 2023 at 16:22
  • The WordPress core function get_posts() that runs on taxonomy page as per default wordpress code to fetch posts in that taxonomy is a bit slow when taxonomy has a lot of posts assigned to it.
    – dc09
    May 17, 2023 at 18:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.