s.kuznetsov
s.kuznetsov

Reputation: 15223

duplicate posts with ajax load more wordpress

I have ajax loading posts on my site when scrolling. The problem lies in the appearance of duplicate posts. I cannot understand why this is happening. Only some posts have duplicates. Here is my code in function.php:

    function loadmore_get_posts(){
      $paged = !empty($_POST['paged']) ? $_POST['paged'] : 1;
      $paged++;
    
      $args = array(
        'paged' => $paged,
        'posts_per_page' => $_POST['posts_per_page'],
        'post_type'      => 'post',
        'post_status' => 'publish',
        'cat' => $_POST['cats']
        );
    
      query_posts($args);
     
      while( have_posts() ) : the_post();
        get_template_part( 'this is template' );    
      endwhile;
      die;
    }
    add_action('wp_ajax_loadmore', 'loadmore_get_posts');
    add_action('wp_ajax_nopriv_loadmore', 'loadmore_get_posts');

And this is ajax in vanilla javascript:

    let ajaxurl = '<?php echo admin_url('admin-ajax.php') ?>';
    let section_posts = 1;
    let postData = new FormData();
    
    postData.append('action', 'loadmore');
    postData.append('paged', section_posts);
    postData.append('posts_per_page', 9);
    postData.append('cats',  <?php print json_encode(get_selected_cats())?>);
    
      const xhr = new XMLHttpRequest();
      xhr.open('POST', ajaxurl);
    
      xhr.addEventListener('readystatechange', function (data) {
      if (this.readyState === 4 && this.status === 200) {
         section_posts++;
         document.querySelector('.articlefeed_template').innerHTML += data.target.responseText;
      } else {}
         xhr.send(postData);
      }

Please, tell me what I am wrong about? Thanks!

Upvotes: 3

Views: 1525

Answers (1)

Parthavi Patel
Parthavi Patel

Reputation: 767

I would suggest NOT to use query_posts and use wp_query instead.

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

    $args = array(
        'paged' => $paged,
        'posts_per_page' => $_POST['posts_per_page'],
        'post_type'      => 'post',
        'post_status' => 'publish',
        'cat' => $_POST['cats']
    );

    $data = new WP_Query( $args );
    $count_posts = $data->found_posts;

    while( $data->have_posts() ) : $data->the_post();
    get_template_part( 'this is template' );    
    endwhile;
    die;
}
add_action( 'wp_ajax_loadmore', 'loadmore_get_posts' );
add_action( 'wp_ajax_nopriv_loadmore', 'loadmore_get_posts' );

Here you will required total post count also , to hide load more button , when posts are finished. Check above code , I have added in $count_posts variable.

Also you have not passed offset ?

In your JS file pass below parameters also

var total_post = '<?php echo $count_posts; ?>';

postData.append('offset', section_posts*9);
postData.append('totalPost', total_post);

Read more about offset here

Upvotes: 1

Related Questions