3

While using the query monitor plugin I could notice I am making a database query 4 times. I am using OPP. So I have a method that gets me a list of posts by querying the database. I have to do this 4 times to allow the user to select the post. I am curious if there is any method by which I can store it and use where ever needed? So making it a single query. ( I am actually querying the list of all ACF fields)

1 Answer 1

1

Generally speaking, you could use the WP Transients API to save the query.

// Get any existing copy of our transient data
if ( false === ( $special_query_results = get_transient( 'special_query_results' ) ) ) {
    // It wasn't there, so regenerate the data and save the transient
     $special_query_results = new WP_Query( 'cat=5&order=random&tag=tech&post_meta_key=thumbnail' );
     set_transient( 'special_query_results', $special_query_results, 12 * HOUR_IN_SECONDS );
}

// Use the data like you would have normally...

This article brings up a good point by arguing that it's not a good idea to store a WP_Query() object as a transient, and instead suggests storing the post IDs returned from an expensive query in a transient, then using those IDs to create a new WP_Query. Granted, with this approach we'd be right back to having duplicate queries, but they would be lighter queries.

$cache_key = 'my-expensive-query';
if ( ! $ids = get_transient( $cache_key ) ) {
    $query = new WP_Query( array(
        'fields' => 'ids',
        // ...
    ) );

    $ids = $query->posts;
    set_transient( $cache_key, $ids, 24 * HOUR_IN_SECONDS );
}

$query = new WP_Query( array(
    'post__in' => $ids,
) );

// while ( $query->have_posts() ) ...
5
  • Thank you. This is new knowledge for me. So are you saying that even if we use the transient API there will be a duplicate query? both parts of your answer is having WP_Query so I don't know what makes a difference. Yes, performance-wise the second option is recommended. a little confused
    – user145078
    Nov 2, 2019 at 5:31
  • With the first example, there would be no duplicate query. With the second example, there would be a duplicate query, but the subsequent queries would be less resource intensive because we'd have all of the IDs. I'd try using the first example, but if you agree with the argument the linked article makes, you could use the second option to avoid serializing a WP_Query instance. Nov 2, 2019 at 6:06
  • Thank you. Did you mean duplicate queries at the time of setting a transient key? as you said subsequent queries would be less resource-intensive.
    – user145078
    Nov 2, 2019 at 6:19
  • In the second example, the duplicate (lighter) queries would occur when using the ids saved in the transient. Nov 2, 2019 at 16:05
  • Maybe DAY_IN_SECONDS is better than 24 * HOUR_IN_SECONDS.
    – Anh Tran
    Apr 24, 2023 at 14:02

Your Answer

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