Get ‘page’ number with infinite scroll

Grabbing the values

Normally you just access the $wp_query object or, in case you did do a custom query like $my_query = new WP_Query();, the $my_query object. From there you can get the $wp_query->numberposts (or better, as non-deprecated: $wp_query->found_posts) for the full amount of posts and $wp_query->posts_per_page for the number of posts per page.

Inside a plugin

Just write a small plugin to do this job for you:

<?php
/* Plugin Name: Infinite Scroll Counter Script */
add_action( 'wp_enqueue_scripts', 'wpse88834_add_script' );
function wpse88834_add_script()
{
    wp_enqueue_script(
        'wpse_counter',
        plugin_dir_url( __FILE__ ).'js/counter.js',
        array( 'jquery' ), // the infinte scroll script should also be added as dependency
        filemtime( plugin_dir_path( __FILE__ ).'js/counter.js' ),
        true
    );
    wp_localize_script(
        'wpse_counter',
        'wpse_counter_obj',
        array(
            'numberposts'    => $GLOBALS['wp_query']->numberposts,
            'found_posts'    => $GLOBALS['wp_query']->found_posts,
            'posts_per_page' => $GLOBALS['wp_query']->posts_per_page,
        )
    );
}

When you’re then inside your script, you can access your data there easily

/* Inside ~/js/counter.js */
jQuery( document ).ready( function($) {
    /* wpse_counter_obj.numberposts */
    wpse_counter_obj.found_posts
    wpse_counter_obj.posts_per_page
    // Current
    var post_count_curr = 0;
    post_count_curr  += wpse_counter_obj.found_posts;
    console.log( post_count_curr  );
} );

Now you just have to add an event listener to the infinite scroll and increment the counter.

Leave a Comment