WordPress.org

Forums

[resolved] How to count posts in paginated loop? (3 posts)

  1. MI
    Member
    Posted 11 months ago #

    Hi,

    I'm using loop and want to count items. This code works on page1, however when you enter page2 it starts from 0.

    <?php
    $post_counter = 0;
    $wp_query = new WP_Query( '&showposts=12' . '&paged='.$paged);
    
    if ( $wp_query->have_posts() ) { ?>
    <?php while ( $wp_query->have_posts() ) {
    $wp_query->the_post();
    $post_counter++;
    ?>
    
    // CONTENT
    
    <?php echo $post_counter; ?>
    
    <?php } ?>
    <?php } else { ?>
    <?php } wp_reset_postdata();?>

    Any help? Thanks

  2. vtxyzzy
    Member
    Posted 11 months ago #

    The following should work for the case you showed:

    // Get the paged variable
    $paged = (get_query_var('paged')) ? get_query_var('paged') :
       ((get_query_var('page')) ? get_query_var('page') : 1);
    
    // Get the number of sticky posts
    $sticky_array = get_option('sticky_posts');
    $sticky_count = sizeof( $sticky_array );
    
    $posts_per_page = 3;
    $post_counter = 0;
    $wp_query = new WP_Query( "posts_per_page=$posts_per_page&paged=$paged");
    if ( $wp_query->have_posts() ) { ?>
       <?php while ( $wp_query->have_posts() ) {
          $wp_query->the_post();
          ++$post_counter;
          if ( $paged == 1 ) $sticky_count = 0;
          $total_posts = (($paged - 1) * $posts_per_page) + $sticky_count + $post_counter ;
          ?>
    
          // CONTENT
    
          <?php echo $total_posts; ?>
    
          <?php echo '<br />'; // Added this while testing ?>
    
    <?php } ?>
    <?php } else { ?>
    <?php }
    wp_reset_postdata();?>

    The situation with sticky posts is complicated. The code above will not work if you set ignore_sticky_posts=1. In that case, you must set $sticky_count = 0; before the query.

    Sticky posts will also make the code fail if you select by category, or tag, a custom taxonomy, and possibly other cases.

  3. MI
    Member
    Posted 11 months ago #

    Perfect :) Thanks for the solution! :)

Reply

You must log in to post.

About this Topic