0

I am using the following code to make my posts infinite loading. But it's weird, for now there are 7 posts on the site, and 6 posts setting for displaying and when I started scroll only one post should display but not, this post is displayed over and over as I scroll the page. I confused. Please could anyone help me to solve this?

jQuery code:

$(window).scroll(function(){
    var bottomOffset = 2000,
        button = $( '#loadmore a' ),
        paged = button.data( 'paged' ),
        maxPages = button.data( 'max_pages' );

    if( $(document).scrollTop() > ($(document).height() - bottomOffset) && !$('body').hasClass('loading')){
        $.ajax({
            type : 'POST',
            url : wp_helper.ajax_url,
            data : {
                paged : paged,
                action : 'loadwork' 
            },
            beforeSend: function( xhr){
                $('body').addClass('loading');
            },
            success:function(data){
                if( data ) {
                    paged++;
                    $('#ifinity-scroll').append( data );
                    lazyLoad();
                    $('body').removeClass('loading');
                }
            }
        });
    }
});

and functions code:

add_action( 'wp_ajax_loadwork', 'post_loadwork' );
add_action( 'wp_ajax_nopriv_loadwork', 'post_loadwork' );

function post_loadwork() {

$paged = ! empty( $_POST[ 'paged' ] ) ? $_POST[ 'paged' ] : 1;
$paged++;

$args = array(
    'post_type' => array( 'location' ),
    'post_status' => 'publish',
    'paged' => $paged
);

query_posts( $args );

   while( have_posts() ) : the_post(); 
    get_template_part('template-parts/content', 'card');
   endwhile;
  die;
 }
2
  • The query looks OK. I'd double check that the paged numbers you're sending it are increasing correctly in your browser's network tab, and trace out the query args on in the function just to make sure that they're what you expect them to be too.
    – Rup
    Nov 5 at 14:00
  • Hi, thanks for the reply. I think the issue is here global $wp_query; $paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1; $max_pages = $wp_query->max_num_pages; if( $paged < $max_pages ) { echo '<div id="loadmore" style="text-align:center;"> <a href="#" data-max_pages="' . $max_pages . '" data-paged="' . $paged . '" class="button">Load more</a> </div>'; } Nov 5 at 21:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.