1

I have the following code to count the number of posts in a specific category. Based on the number of posts that it returns it should do something.

$args = array(
    'posts_per_page' => -1,
    'post_type' => 'post',
    'cat' => '9',
);

$count_query = new WP_Query( $args );
$count = $count_query->post_count;

if ( $count >= 3) {

// do something     

}

This code works but only if I include posts_per_page in my array. Can someone explain me why this is?

I expected the code to work without the post_per_page as well. Instead it returns a 0 as result.

2

Well... It's pretty easy to explain...

Problem explanation

Your code doesn't count anything - it retrieves posts that matches given query (you query posts that are in category with ID 9). If you provide no posts_per_page param, then default value is used (the one that is set in Settings). On the other hand, if you set posts_per_page to -1, then you'll get all posts that matches given query. But doing so is very bad idea - if there are thousands of posts, then you'll retrieve all of them from DB just to count them.

Solution

One way to fix this would be to check found_posts instead of post_count. First one is "The total number of posts found matching the current query parameters" and the second one "The number of posts being displayed".

$args = array(
    'post_type' => 'post',
    'cat' => 9,
);

$count_query = new WP_Query( $args );
$count = $count_query->found_posts;

if ( $count >= 3) {
    // do something
}

Better solution

But... There is much more efficient way to get count of posts in given category...

$category = get_category( 9 );  // <- change the ID of category

if ( $category->category_count >= 3 ) {
    // do something
}

Of course you should also check if the given category exists and so on.

  • Thanks @krzysiek-dróżdż ! That's an a very detailed and helpful explanation. Much appreciated :-) – NielsPilon Mar 21 '18 at 12:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.