Helping you build a better website
(and other interesting web stuff)

CSSHTMLJavaScriptjQueryMySQLPHPSilvaTechnologiesWooCommerceWordpress
Silva Web Designs - Blog

Load More Posts Ajax Button in WordPress

Updated: 20/07/2020 – Further clarification has been added on the setup of this script.

In today’s post, we will show you how to create a load more button to show additional posts or custom post types using AJAX.

The benefit of this is that it will improve the page-load of the particular page as it will only be displaying a certain amount of posts before having to load any more of the content (especially when you are loading images).

So let’s get started…

So the first thing that you should have is a list of posts to display on the frontend as follows:-


    <div id="ajax-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="small-12 large-4 columns">
                <h1><?php the_title(); ?></h1>
                <p><?php the_content(); ?></p>
         </div>

         <?php
                endwhile;
        wp_reset_postdata();
         ?>
    </div>
    <div id="more_posts">Load More</div>

Then you want to add the following code in your functions.php file where you register the scripts:


	wp_localize_script( 'core-js', 'ajax_posts', array(
	    'ajaxurl' => admin_url( 'admin-ajax.php' ),
	    'noposts' => __('No older posts found', 'twentyfifteen'),
	));	

NOTE: You will need to replace code-js with the file you are going to be adding the JS code later in this tutorial.

We added it to a file called core.js, and the reason we added code-js is that we enqueued the script as follows:


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

Right after the existing wp_localize_script. This will load WordPress own admin-ajax.php so that we can use it when we call it in our ajax call.

At the end of the 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');

The final part is the ajax itself. In functions.js or your main JavaScript/jQuery file, you need to input inside the $(document).ready(); environment the following code:-


var ppp = 3; // Post per page
var pageNumber = 1;


function load_posts(){
    pageNumber++;
    var str = ''&pageNumber=' + pageNumber + '&ppp=' + ppp + '&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-posts").append($data);
                $("#more_posts").attr("disabled",false);
            } else{
                $("#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.
});

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

How to add Infinite Load, instead of Click

You can also load the rest of the posts automatically on scroll instead of having to click on a button. This can be achieved by making it invisible by setting the visibility to hidden.

The following code will run the load_posts() function when you’re 100px from the bottom of the page. So instead of the click function we added we would use:


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

Do note that there is a drawback to this. With this method, you could never scroll the value of $(document).height() - 100 or $('footer').offset().top, If that should happen, just increase the number where the scroll goes to.

You can easily check it by putting console.log in your code and see in the inspector what they throw out like so:


$(window).on('scroll', function () {
    console.log($(window).scrollTop() + $(window).height());
    console.log($(document).height() - 100);
    if ($(window).scrollTop() + $(window).height()  >= $(document).height() - 100) {
        load_posts();        
    }
});

Adjust the settings accordingly and you will get this working to your desire in no time!

If you need any help with this, feel free to get in touch in the comment below. If you need help with this, just drop me a message and I’ll be more than happy to help you!

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well of many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

23 thoughts on “Load More Posts Ajax Button in WordPress

  1. Hey. I am getting this error
    ReferenceError: Can’t find variable: ajax_posts.

    Looks like this is only for twentyfifteen theme? I am trying to use it on my custom theme. I copied things from twentyfifteen, but it didn’t change anything about this error.

    1. The code will work with any theme, do you have a link that I can check? You shouldn’t be getting an error if the code has been added to your functions.php file.

  2. Edit: after copying functions.js and enqueuing it error disapeared but posts are still not loading. every click loads admin-ajax.php and that’s all.

    1. I have a different issue probably, even pagination didn’t show up. It is copied code for custom loop, so I don’t know why. I am working on it.

  3. Nooow I got it. I was using different post type and I didn’t realize I had to change it in the functions.php part too, damn, so much time wasted for this.

    1. Sorry one last reply πŸ˜€
      To be helpful too, I found a typo. There is one extra quote here / ”&pageNumber=’ /

      1. Haha, I realised there was a bit of confusion in setting this up. I’m glad you’ve resolved the issue, I’ve updated the post to clarify things and also corrected the issue with the additional quote ; ) Thanks for raising that for me, I’m sure it will help others.

  4. Would really appreciate some help with this, my current query has 24 posts per page and I use:
    $index = 1; $totalNum = $wp_query->found_posts;
    to put each set of 3 inside a div with class “row”.
    So on the news page I currently have:
    row
    post 1
    post 2
    post 3
    end of row
    row
    post 4
    post 5
    post 6
    end of row etc…

    How can I get this same effect when load more is clicked? I have tried to insert the same type of query and echo a div with class row but it just doesnt seem to add the new posts inside the row div.
    Thanks

    1. Hi Adrian,

      Can you further explain the issue that you are having, or do you have a development link where I can see the issue that you are facing? I’l be able to provide a solution once you send me this.

      Thanks,

      Nathan

    1. Ahhh okay, I can see the issue now.

      What you need to do is replace the more_post_ajax part in in your functions.php with the following:-

      
      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 = '';
      
      	$out = '<div class="row">';
          if ($loop -> have_posts()) :  $i = 1; while ($loop -> have_posts()) : $loop -> the_post();    	
              $out .= '<div class="post">;
                      	<h1>'.get_the_title().'</h1>
                      	<p>'.get_the_content().'</p>
             			</div>';
             	if($i % 3 == 0) {$out .= '</div><div>';}
      
          $i++; 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');
      

      The $out variable is what is being outputted in the HTML code when you click load more.

      In your case scenario, you are loading 3 items at a time, so I added the <div class="row"> outside of the loop and then echoing the closing div for this element every 3 elements, hope that makes sense.

      I think I will update this post with a more updated version, I think some more clarity needs to be made on this post.

      1. Hi Nathan

        Thank you for the help so far, almost there. If you take another look now you’ll see your code worked a treat, but there seems to be an extra empty row div at the end after the row of posts, if you click load more a few times theres a row with 3 posts then an empty div then another row then an empty one. The load more button is also appearing inside a row div where it’s not in the template (presumably for the same reason). And any way of the posts appearing above the load more button not below it?

        1. Okay, sorry my bad, please change the code to:

          
          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 = '';
          
          	$out = '<div class="row">';
              if ($loop -> have_posts()) :  $i = 1; while ($loop -> have_posts()) : $loop -> the_post();    	
                  $out .= '<div class="post">
                          	<h1>'.get_the_title().'</h1>
                          	<p>'.get_the_content().'</p>
                 			</div>';
                 	if($i % 3 == 0) {$out .= '</div>';}
          
              $i++; 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');
          

          Then, to append the ‘load more’ to always appear at the end of the posts, please update your JS for the click function to:

          
              $("#more_posts").on("click",function(){ // When btn is pressed.
                  $("#more_posts").attr("disabled",true); // Disable the button, temp.
                  load_posts();
                  $(this).insertAfter('#ajax-posts');
              });
          

          Should be all good now πŸ˜‰

          1. Hi Nathan
            Thanks again for your further reply, I have finally got the ajax loading working, my total post count wasn’t returning the correct figure so when I used $i = $totalNum it wasn’t stopping the rows from being added hence the additional divs being created at the end.
            So the loading is all working great now, unfortunately the only thing not working at this point is the load more link being at the end, I added $(this).insertAfter(‘#ajax-posts’); as suggested but this didn’t work. Also tried $(this).appendTo($(‘#ajax-posts’));

          2. That’s odd, it’s working on my test site with $(this).insertAfter('#ajax-posts');

            You could try adding it here:

            
            if($data.length){
                $("#ajax-posts").append($data);
                $("#more_posts").attr("disabled",false);
                $(this).insertAfter('#ajax-posts'); // Add here
            }
            

            It actually seems to work on the second click though which is strange.

            What happens if you add a short delay, like:

            
            setTimeout(function(){
                $(this).insertAfter(β€˜#ajax-posts’);
            },500);
            

            It could be possible the element is being moved before the element has time to populate.

            Pretty sure one of the 2 suggestions above will work anyway. Let me know : )

    2. I have also updated the post now to clarify a few things on the setup of this, let me know if the code above fixes the issue you are having : )

  5. Hi,
    I’m trying to get the load more button to work for my page.
    But I’m getting this error: “Uncaught ReferenceError: ajax_posts is not defined”
    I used localized script after the script.js has been added.

    Do you have an idea what I’m doing wrong?

Join the discussion