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

Outsourcing vs Offshoring: Which Strategy is Right for Your Business?

Outsourcing vs Offshoring: Which Strategy is Right for Your Business?

In today's competitive business environment, companies are constantly looking for ways to optimize costs, improve efficiency, and access global talent. Outsourcing and offshoring are two popular s

Read More
How to Create a Meaningful Memorial Website

How to Create a Meaningful Memorial Website

A heartfelt approach to honoring and remembering a loved one is to create a memorial website, which gives family and friends a digital platform to do the same. This comprehensive tutorial will show yo

Read More
H

How to get last insert ID in PHP Codeigniter?

In this article, we are going to discuss how to get the last inserted ID in Codeigniter. I will let you know how to get the last inserted id from the table. Sometimes, You have to work on relational t

Read More