WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Is there a way to know the total number of posts before the loop starts? I'm thinking in use two loops. The first will do the counting, while the second one will handle the content. However, I don't think this approach is 'elegant'. Any other solutions?

share|improve this question
up vote 5 down vote accepted


function wpse8170_get_posts_count() {
    global $wp_query;
    return $wp_query->post_count;


if (have_posts()) :
    echo '<h1>' . wpse8170_get_posts_count() . ' Posts Found</h1>';

    while ( have_posts() ) : 
share|improve this answer
I'm trying to customise the query with the below code function wpse8170_get_posts_count() { $args = array( 'ignore_sticky_posts' => true, 'post_status' => 'publish' ); $wp_query = new WP_Query( $args ); global $wp_query; return $wp_query->post_count; } But it's showing exactly the double of posts. – Daniel Jan 9 '13 at 12:14
@Daniel remove global $wp_query; from your version of function. – Eugene Manuilov Jan 9 '13 at 12:18

The number of all posts for a given query is in $GLOBALS['wp_query']->found_posts.

The number of all posts for just the page you are seeing is in $GLOBALS['wp_query']->post_count.

To see all available variables test it with:

add_action( 'loop_start', function() {
    print '<pre>'
        . htmlspecialchars(
            print_r( $GLOBALS['wp_query'], TRUE ),
        . '</pre>';
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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