How to count posts in loop with infinite scroll?

on my index.php I display all my posts with infinite scroll. Before the WP loop I added a $counter, which counts up with every post. But if the infinite scroll loads new posts, the counter will be reset.

Example for counter: 0 1 2 3 4 5 6 7 (load new posts) 0 1 2 3 4 . . .

What can I do that the counter counts up after loading new post (...,6,7,8,9,10,...)?

Thanks for help!

div class="grid" id="container"
    div class="grid-sizer"/div
        ?php $counter = 0;
            if ( have_posts() ) {
                while ( have_posts() ) {
                    the_post();?
                    div class="grid-item post-item?php if($counter % 4 == 0) : ? opening-box?php endif; ?"
                        ?php the_content(); ?
                    /div
               ?php $counter++; 
               } // end while
            } ?
     /div
/div

Topic infinite-scroll wp-query Wordpress

Category Web


You don't need to set your own counter. WP_Query offers a method that holds the current post's number, just like the key for an array in a foreach loop.

To access the current post, use $wp_query->current_post and as mentioned by the other answer, you can use $count = $wp_query->found_posts to count the total of found posts.


Maybe try adding this before the loop:

$count = $wp_query->post_count;

But that may only return the number of posts you have set for posts_per_page, in that case you might be able to use:

$count = $wp_query->found_posts;

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.