1

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!

2
  • 1
    Your code sets section_posts to 1 before every request, so you’re always going to get the same page. Commented Dec 21, 2021 at 2:38
  • @JacobPeattie, Thanks for your reply. The problem is that some posts are duplicated. Commented Dec 21, 2021 at 8:24

1 Answer 1

0

Firstly your cat parameter expects an array and you're passing a json string to it... You need to json_decode back your array of posts to run through the query.

Secondly, you are using query_posts() which if you look at the codex page reads:

Note: This function will completely override the main query and isn’t intended for use by plugins or themes. Its overly-simplistic approach to modifying the main query can be problematic and should be avoided wherever possible. In most cases, there are better, more performant options for modifying the main query such as via the ‘pre_get_posts’ action within WP_Query.

This must not be used within the WordPress Loop.

So, fix the cat issues and use get_posts() or WP_Query here and I'd be very surprised if you still have issues.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.