4

This is potentially a duplicate but what was listed on the following link didn't work for me : Return only Count from a wp_query request?

I can't get the count using the query below. If I set posts_per_page = -1 it renders a blank page, if I set it to something like 10, it returns 10 found_posts..

There's 190k results with "special_key", so maybe something to do with it..?

// There are 190k records with post_meta "special_key" on each coupon/post.
$query = array(
    'post_type' => 'shop_coupon',
    'meta_key' => 'special_key',  
    'fields' => 'ids',
    'no_found_rows' => true,    
);

$results = new WP_Query($query);
echo $results->found_posts; //// This is 0...
echo $results->count_posts; //// This is 0...
wp_reset_postdata();

If it helps, I'm running the query from inside a plugin.

2

1 Answer 1

6

The found_posts property of the WP_Query class is what you're looking for, which is the amount of found posts for the current query. However, you got a 0 because you set no_found_rows (in the $query array) to true, which means the amount there will not be calculated. I.e.

  • WordPress will not append SQL_CALC_FOUND_ROWS to the SQL command for querying the posts. Otherwise, the command would be something like: SELECT SQL_CALC_FOUND_ROWS {the rest of the query}

  • WordPress will not execute SELECT FOUND_ROWS() after the posts query is complete. And when it's not executed, the value of the found_posts property would be a zero (0).

So remove the no_found_rows from the $query array, and the $results->found_posts would have the proper value:

$query = array(
    'post_type' => 'shop_coupon',
    'meta_key' => 'special_key',
    'fields' => 'ids',
);
4
  • 1
    But I have no_found_rows set to true? I'll give that exact copy paste a try and report back.
    – Darius
    Commented Aug 24, 2018 at 0:31
  • Lol sorry, that false was a typo. I've corrected it. (and previously added more details)
    – Sally CJ
    Commented Aug 24, 2018 at 0:37
  • 2
    Ahh, I see. I REALLY wish the documentation used your explanation. That makes sense and it worked. The biggest confusion was the no_found_rows, setting it to true or false actually messed with the query, omitting it helped, alongside ids.
    – Darius
    Commented Aug 24, 2018 at 0:55
  • Setting no_found_rows to false should also work, although I wouldn't set no_found_rows if I were to set its value to false since that's the default value. Anyway, I'm glad the answer helped you. =)
    – Sally CJ
    Commented Aug 24, 2018 at 1:20

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.