Home > Software engineering >  Does WordPress function get_post(post_id) query the database?
Does WordPress function get_post(post_id) query the database?

Time:01-15

In my WordPress theme the theme author first makes a database query to get all active posts to get post IDs like this:

$SQL = "SELECT post_id FROM mytable_postmeta 
            WHERE meta_key = 'expiry_date' AND CAST(meta_value AS DATETIME) >='2023-01-14 12:00:00'"
$posts_found = $wpdb->get_results($SQL, OBJECT);

Then he later loops over the results and get each posts by it's ID like this:

foreach($posts_found as $single_post){   
    global $post;
    $post = get_post($single_post->ID);                                              
} 

My question is if this is a database query to get all post IDs and then one database query for each post in the foreach loop? I.e., does the get_post WordPress function query the database once per post in the loop?

If so, can I re-write this in a smart way to reduce the number of database calls?

CodePudding user response:

Sure there is, try this:

$SQL = "SELECT post_id FROM mytable_postmeta 
            WHERE meta_key = 'expiry_date' AND CAST(meta_value AS DATETIME) >='2023-01-14 12:00:00'";

$post_ids = $wpdb->get_col($SQL);
$posts = get_posts([
    'include' => $post_ids,
    'post_status' => 'publish'
]);

or even better, using meta_query

$posts = get_posts([
    'meta_query' => [
        [
            'key' => 'expiry_date',
            'value' => '2023-01-14 12:00:00',
            'compare' => '>=',
            'type' => 'DATETIME'
        ]
    ],
    'post_status' => 'publish'
]);

Yes, get_post does perform an additional query each time it is called.

  • Related