1

I am trying to create a function to load more posts via AJAX by clicking a button on my blog page. The blog page initially loads 9 posts like this:

<?php
    $postsPerPage = 9;
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => $postsPerPage
    );

    $loop = new WP_Query($args);

    while ($loop->have_posts()) : $loop->the_post();
?>

<div class="post">
    <h2><?php the_title(); ?></h2>
    <?php the_content(); ?>
</div>

<?php endwhile; wp_reset_postdata(); ?>

Then I have the following function in my functions file:

function more_post_ajax(){

    $ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 9;
    $page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;

    header("Content-Type: text/html");

    $args = array(
        'suppress_filters' => true,
        'post_type' => 'post',
        'posts_per_page' => $ppp,
        'paged' => $page,
    );

    $loop = new WP_Query($args);

    $out = '';

    if ($loop -> have_posts()) :  while ($loop -> have_posts()) : $loop -> the_post();
        $out .= '<div class="post">
                    <h2><?php the_title(); ?></h2>
                    <?php the_content(); ?>
                </div>';

    endwhile;
    endif;
    wp_reset_postdata();
    die($out);
}

add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');

And the following Javascript to load more posts on the click of a button:

function load_posts(){
    pageNumber++;
    var str = '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
    $.ajax({
        type: 'POST',
        dataType: 'html',
        url: theme.ajaxurl,
        data: str,
        success: function(data) {
            var $data = $(data);
            if($data.length){
                $('.posts').append($data);
            }
        },
        error : function(jqXHR, textStatus, errorThrown) {
            $loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
        }

    });
    return false;
}

This all works fine in terms of loading more posts, the only problem is that the last post of the initial load is duplicated when you load more posts so it is in both the 9th and 10th position. Any ideas how to resolve this?

  • 1
    In your Javascript, what is pageNumber and where is it defined? What is the default? – Howdy_McGee Sep 25 '17 at 15:26
  • pageNumber is 0 by default, so the first time load_posts() is called, it changes to 1 – user13286 Sep 25 '17 at 16:26

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.