blog images
How to Load More Posts using Ajax with a Button or on Scroll in WordPress

In this article we will show you how to create a load more button to show more posts or custom post types using AJAX. In this way we can show more post without loading a page. Loading speed of the page will be increased

Follow the step by step process to implement Ajax based load more option

Step 1: Create a Template file

Create a Template file in wordpress where you can add client code

<div id="ajax-load-posts" class="row">

        <?php

            $postsperpage = 3;

            $args = array(

                    'post_type' => 'post',

                    'posts_per_page' => $postsperpage,

            );

 

            $loop = new WP_Query($args);

 

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

        ?>

 

         <div class="col4">

                <h1><?php the_title(); ?></h1>

                <p><?php the_content(); ?></p>

         </div>

 

         <?php

                endwhile;

        wp_reset_postdata();

         ?>

    </div>

    <div id="load_more_posts">Load More</div>

Step 2:  Add Ajax script in Template file

Add the ajax call function in Template file. Use the ajax call in Document ready function

$document.ready(function({
var p = 3; // Post per page

var pageNo = 1;

 

 

function load_posts(){

    pageNo++;

    var str = '&pageNo=' + pageNo + '&p=' + p + '&action=more_post_ajax';

    $.ajax({

        type: "POST",

        dataType: "html",

        url: ajax_posts.ajaxurl,

        data: str,

        success: function(data){

            var $data = $(data);

            if($data.length){

                $("#ajax-load-posts").append($data);

                $("#load_more_posts").attr("disabled",false);

            } else{

                $("#load_more_posts").attr("disabled",true);

            }                 

        },

        error : function(jqXHR, textStatus, errorThrown) {

            $loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);

        }

 

    });

    return false;

}

 

$("#more_posts").on("click",function(){ // When btn is pressed.

    $("#more_posts").attr("disabled",true); // Disable the button, temp.

    load_posts();

    $(this).insertAfter('#ajax-posts'); // Move the 'Load More' button to the end of the the newly added posts.

});

});         

Step 3: Add following in Function.php file

Then you want to add the following code in your functions.php

wp_localize_script( 'core-js', 'ajax_posts', array(

                  'ajaxurl' => admin_url( 'admin-ajax.php' ),

                  'noposts' => __('No older posts found', 'blazingcoders'),

              ));

After adding wp_localize_script load the default admin-ajax.php so that we can use in our ajax call and also add code.js function to register the script.                       

wp_register_script( 'core.js', get_template_directory_uri() . '/assets/js/core.js');

wp_enqueue_script( 'core.js' );

At last add the following code in functions.php file, you need to add the function that will load your posts:-

 

function more_post_ajax(){

 

    $ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3;

    $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="small-12 large-4 columns">

                <h1>'.get_the_title().'</h1>

                <p>'.get_the_content().'</p>

         </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');

 

Step 4: Infinity Scroll

 

Add the infinity scroll function below function is used to load infinity scroll

 

$(window).on('scroll', function(){

    if($('body').scrollTop()+$(window).height() > $('footer').offset().top){

        if(!($loader.hasClass('post_loading_loader') || $loader.hasClass('post_no_more_posts'))){

                load_posts();

        }

    }

});