Home > Software design >  Existence of posts from complex WP_Query
Existence of posts from complex WP_Query

Time:08-27

I have a comparative set of arguments for WP_Query involving a custom field.

On a page I need to say "Are there going to be results?, if so display a link to another page that displays these results, if not ignore" There are between 500 and 1200 posts of this type but could be more in the future. Is there a more efficient or direct way of returning a yes/no to this query?

 $args = array(
    'post_type' => 'product',
    'posts_per_page' => -1,
    'meta_query' => array(
         array(
           'key'      => 'partner',
           'value'    =>  $partner,
           'compare' => 'LIKE',
            ),
           ),
         );

$partner_query = new WP_Query($args);
if ($partner_query->have_posts() ) { [MAKE LINK] }

The link is not made from data returned, we already have that information.

Perhaps directly in the database. My SQL is not up to phrasing the query which in English is SELECT * from wp_posts WHERE post_type = 'product'} AND (JOIN??) post_meta meta_key = partner AND post_id = a post_id that matches the first part of the query.

And if I did this, would this be more efficient that the WP_Query method?

CodePudding user response:

Use 'posts_per_page' => 1 and add 'no_found_rows' => true and 'fields' => 'ids'. This will return the ID of a matching post, and at the same time avoid the overhead of counting all the matching posts and fetching the entire post contents. Getting just one matching post id is far less work than counting the matching posts. And it's all you need.

Like this:

 $args = array(
    'post_type'      => 'product',
    'posts_per_page' => 1,
    'no_found_rows'  => true,
    'fields'         => 'ids',
    'meta_query' => array(
         array(
           'key'      => 'partner',
           'value'    =>  $partner,
           'compare' => 'LIKE',
            ),
           ),
         );

$partner_query = new WP_Query($args);
if ($partner_query->have_posts() ) { [MAKE LINK] }

no_found_rows means "don't count the found rows", not "don't return any found rows". It's only in the code, not the documentation. Sigh.

  • Related