Quantcast
Channel: Question and Answer » json
Viewing all articles
Browse latest Browse all 148

WordPress ajax load more returns duplicated posts

$
0
0

I’m trying to load more posts from my custom post type via ajax call, it sounds like i’m doing everything alright but one thing which is causing the duplication issue.

My load more button does work fine but there are some duplication on it which i thought maybe i’m doing something wrong with the pagination?
the way i’m sending the current page number within the ajax is below :

 var Paged = 1;

and inside the ajax code

data: {
      action: 'get_team_members',
      paged: ++Paged
},

Here is my page code which should load the data on it:

  global $wp_query, $paged;

  $paged = get_query_var('paged') ?: 1;

  $args = array(
      'post_type' => 'team',
      'paged' => $paged,
      'posts_per_page' => 19,
  );

  $wp_query = new WP_Query($args);

<?php
    if ( $wp_query->have_posts() ):   
       while ( $wp_query->have_posts() ): $wp_query->the_post();
        ?>
        <?= the_title(); ?>
       <?php endwhile; ?>
<?php endif; ?>
    <button class="btn-lazy-load"></button>

i’m not including the jQuery because i’m pretty sure the issue is with my query.

And here is my function which is inside the functions.php

add_action( 'wp_ajax_get_team_members', 'get_team_members' );
add_action( 'wp_ajax_nopriv_get_team_members', 'get_team_members');

function get_team_members() {
    $paged = intval($_POST['paged']) ?: 1;

    $members = array();
    $args = array(
        'post_type' => 'team',
        'paged' => $paged,
        'posts_per_page' => 19,
    );

    $the_query = new WP_Query($args);
    error_log(print_r($the_query, true));
    if ( $the_query->have_posts() ) {
        while ( $the_query->have_posts() ) {
            $the_query->the_post();
            $members[] = array(
                'title' => get_the_title(),
            );
        }
    }
    echo json_encode($members);
    wp_die();
}

Do you guys have any thoughts what i’m doing wrong here?


Viewing all articles
Browse latest Browse all 148

Trending Articles