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:
add_action('pre_get_posts',function($query){
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 );
set_transient($key,$query_result,HOUR_IN_SECONDS);
return $query_result;
});
The above code is not working. How to achieve this?