How To Load More Post With Ajax In WordPress

In this article, we will learn you how to create a load more button to show additional posts or custom post types using AJAX.

The load more post button works like infinite scroll.Instead of loading whole page it will only be displaying a certain amount of posts before having to load any more of content.

Learn more about how to create child theme in WordPress from our article How To Create Child Theme in WordPress

list of posts to display on the Front-end as follows:

1.  First Create one template file in your child theme folder and add below code.

<?php 
  /*
  Template Name: blog Page
  */
  get_header(); ?>
  <div class="wrap">
    <div id="primary" class="content-area">
      <?php $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'posts_per_page' => '2',
        'paged' => 1,
      );
      $blog_posts = new WP_Query( $args ); ?>
      <?php if ( $blog_posts->have_posts() ) : ?>
        <div class="blog-posts">
          <?php while ( $blog_posts->have_posts() ) : $blog_posts->the_post(); ?>
            <h2><?php the_title(); ?></h2>
            <?php the_excerpt(); ?>
          <?php endwhile; ?>
        </div>
        <div class="loadmore">Load More</div>
        <span class="no-more-post"></span>
      <?php endif; ?>
    </div>
  </div>
  <?php get_footer();

This will display two post per page.

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

<?php
  function thecodehubs_enqueue_script_style() {
    wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css', array(), '1.0.0', 'all');
    wp_register_script( 'custom-script', get_stylesheet_directory_uri(). '/js/custom.js', array('jquery'), false, true );
    // Localize the script with new data
    $script_data_array = array(
      'ajaxurl' => admin_url( 'admin-ajax.php' ),
      'security' => wp_create_nonce( 'load_more_posts' ),
    );
    wp_localize_script( 'custom-script', 'blog', $script_data_array );
    // Enqueued script with localized data.
    wp_enqueue_script( 'custom-script' ); 
  }
  add_action( 'wp_enqueue_scripts', 'thecodehubs_enqueue_script_style' );


  function load_posts_by_ajax_callback() {
    check_ajax_referer('load_more_posts', 'security');
    $paged = $_POST['page'];
    $args = array(
      'post_type' => 'post',
      'post_status' => 'publish',
      'posts_per_page' => '2',
      'paged' => $paged,
    );
    $blog_posts = new WP_Query( $args ); ?>
    <?php if ( $blog_posts->have_posts() ) : ?>
      <?php while ( $blog_posts->have_posts() ) : $blog_posts->the_post(); ?>
        <h2><?php the_title(); ?></h2>
        <?php the_excerpt(); ?>
      <?php endwhile; 
    endif;
    wp_die();
  }
  add_action('wp_ajax_load_posts_by_ajax', 'load_posts_by_ajax_callback');
  add_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_posts_by_ajax_callback');

3. now open custom.js file and add the below code to it.

jQuery( document ).ready( function(){
    var page = 2;
    jQuery( function($) {
      jQuery( 'body' ).on( 'click', '.loadmore', function() {
        var data = {
          'action': 'load_posts_by_ajax',
          'page': page,
          'security': blog.security
        };
        jQuery.post( blog.ajaxurl, data, function( response ) {
          if( $.trim(response) != '' ) {
            jQuery( '.blog-posts' ).append( response );
            page++;
          } else {
            jQuery( '.loadmore' ).hide();
            jQuery( ".no-more-post" ).html( "No More Post Available" );
          }
        });
      });
    });
  });

Create one page and select the “blog Page” template from the admin side.

With the above code, you should now have a load more button at the bottom of your posts where on click it will display further posts. This can also be used with CTP (custom post types).

Output:

Submit a Comment

Your email address will not be published. Required fields are marked *

Footer Logo

Subscribe

Select Categories