How can i get count from query post

The question:

How can i get the row counts in query post like mysql count(*).

$obj_name = new WP_Query($args);

while ($obj_name->have_posts()) : $obj_name->the_post(); 

// here i want to predict looping counts


How can i do this.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

$num = $obj_name->post_count; 

Reference: wp_query

Method 2

The accepted answer here is wrong which is also confirmed in my situation.
Please, compare from the referenced page:

$post_count The number of posts being displayed.

$found_posts The total number of posts found matching the current query parameters

This way, $post_count will show, for example, number of posts per page if there are more than one page of results. Only if total number is less than number of results per page it will match total amount.

The correct method to get total results number is:


Method 3

To get the total number of posts WP_Query returns use “found_posts”

Here is the example –

           $args = array(
           'post_type' => 'post'
        $the_query = new WP_Query( $args );
        $totalpost = $the_query->found_posts; 

Use your custom post type name in place of ‘post’, you can also pass the category id too ( ‘cat’ => 4,)

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment