I added infinite scroll support of the Jetpack plugin to my own theme using this tutorial:

add_theme_support( 'infinite-scroll', array(
    'container'  => 'content',
    'footer' => false,
    'render' => 'vividflow_infscroll_render',
    'wrapper' => 'post_summaries',
    'posts_per_page' => 12,
    'type' => 'scroll'
) );

Now I need something like a counter which increments every time additional posts are loaded.

I know that the new posts are placed in an infinite-view-n class and I have a JavaScript function which I want to call on that new loaded class:

function setupPostSummaries(counter) {
    jQuery('.infinite-view-'+counter).doSomething();
}

So I guess I need a PHP variable in the infinite scroll render function or the loop which increments every time additional posts are loaded. Then I can do in the end of The Loop:

<script type="text/javascript">setupPostSummaries(<?php the_counter(); ?>);</script>

Is such a variable there already? Or is there an other way to achieve my goal?

3 s
3

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 Reply

Your email address will not be published. Required fields are marked *