WordPress

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:

Hetal Rathod

Hetal Rathod is Wordpress Developer, and Author at thecodehubs.com.

View Comments

  • Thanks so much for this code! I tried 2 other tutorials on how to do this and both didn't work.

    Just a small anomaly - I have posts numbered from 10-1 and I only show 10 and 9 first (perfect - 2 posts to begin with). When I click the "Load More" button, it loads posts 8 and 7 twice, so the posts that now show are 10, 9, 8, 7, 8 and 7 again.

    Any idea why it's showing duplicates of the next lot of posts?

    • Actually, to amend to my query, your code works perfectly. All I am trying to do is convert it to 3 initial posts and then show 3 after. I'm just having trouble coding this as I'm not hugely skilled at PHP.

      Thanks so much in advance for any support with this.

  • This is working great! Any idea how I would add a class to a loading/spinner div when the button is clicked and then remove the class when ajax has finished loading?

Share
Published by
Hetal Rathod

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

2 years ago