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

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

 

 

       

            $postsperpage = 3;

            $args = array(

                    'post_type' => 'post',

                    'posts_per_page' => $postsperpage,

            );

 

            $loop = new WP_Query($args);

 

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

        ?>

 

        

 

               

 

               

 

        

 

 

        

                endwhile;

        wp_reset_postdata();

         ?>

   

 

   

Load More

 

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 .= '

 

               

'.get_the_title().'

 

               

'.get_the_content().'

 

        

';

 

 

    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();

        }

    }

});

 

 

Tags

  • WordPress ajax load more posts on scroll without plugin

  • WordPress ajax load more custom query

  • Ajax load more WordPress tutorial

  • Load more posts ajax WordPress plugin
  • Load next WordPress posts with ajax
  • Ajax load more on scroll

  • WordPress ajax load more custom post type plugin

  • Ajax load more pagination

Related Posts

The Future of Corporate Travel: Key Feature of Modern Travel Management Software

The Future of Corporate Travel: Key Feature of Modern Travel Management Software

In today's hectic travel environment, effectiveness and planning are critical. The correct tools can make all the difference, whether you are an individual organizing a holiday or a business execu

Read More
S

Security Testing Company India

The major concerns of an application developer and the client today are software security. Security is vulnerable in all industries such as Healthcare, Banking, Forensic, Media. Our testers majorly us

Read More
H

How to convert an HTML element or document into image ?

In this article, I will be able to show you ways to convert Html div to a picture using JQuery. Here, I'm generating an HTML div element on the client-side to im

Read More