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

Updated: 22/09/2021 – 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'),
	));	

To further explain this, in my example I enqueue scripts as follows:


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

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

Firstly, you would enqueue the file where you will be adding the JS code to, then you will add the wp_localize_script code after you have enqueued the core.js file. This has to be done like this otherwise you will get an error such as Can’t find variable: ajax_posts.


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 core.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); // Uncomment this if you want to disable the button once all posts are loaded
                $("#more_posts").hide(); // This will hide the button once all posts have been loaded
            } 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!

 


Sponsor

If you have come this far and you’re a fan of Football, check out our sponsor below; The FPL Way

They will help you become the king of your FPL mini-leagues!


Fantasy Premier League – Gain the FPL advantage you deserve

 

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 as 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

How to Display Related Posts in WordPress

In this tutorial, we are going to show you two ways to display related posts on your WordPress website.

If you know a bit about bounce rate, you are probably already showing related posts on your website. Essentially, the bounce rate is a metric that measures the percentage of people who land on your website and do completely nothing on the page they entered. So they don’t click on a menu item, a ‘read more’ link or any other internal links on the page. This can have an effect on things such as your AdSense earnings. By following this tutorial and adding Related Posts to your WordPress; you are killing three birds with one stone. You are decreasing your bounce rate, increasing your AdSense income, and lastly, you are increasing your page views. As always, we will show you two methods in which you can add related posts to your WordPress website.

How to Display Related Posts in WordPress without a Plugin

As always, we start with our preferred method of adding this without a plugin. In our example, we are going to display two related posts which link to the post. We are adding the featured image, the category, the date, the title and a read more button.

The code can simply be pasted into your single.php file in a position in which you want to display your related posts.


// Related Posts
$tags = wp_get_post_tags($post->ID);
if ($tags) {
	echo '<h3>Related Posts</h3>';
	$first_tag = $tags[0]->term_id;

	$args=array(
		'tag__in' => array($first_tag),
		'post__not_in' => array($post->ID),
		'posts_per_page' => 2, // How many Posts to display
		'caller_get_posts' => 1 // A way to turn sticky posts off in a query.
	);
	$my_query = new WP_Query($args);
	if( $my_query->have_posts() ) {
		while ($my_query->have_posts()) : $my_query->the_post(); ?>										
			<a href="<?php the_permalink(); ?>">
				<?php if(get_the_post_thumbnail_url()) { ?>
    				<img alt="Related - <?php the_title(); ?>" src="<?php echo get_the_post_thumbnail_url(); ?>" />
    			<?php } else { ?>
    				<div class="img-holder"></div>
    			<?php } ?>	
			</a>												
			<?php $category = get_the_category(); ?>
			<p><?php echo $category[0]->cat_name; ?> / <?php echo get_the_date(); ?></p>													
			<a href="<?php the_permalink() ?>" rel="bookmark"><h4><?php the_title(); ?></h4></a>
			<a class="btn" href="<?php the_permalink(); ?>">Read More</a>
	<?php
	endwhile;
	}
wp_reset_query();
}

How to Display Related Posts in WordPress with a Plugin

A plugin can be used instead to do a similar thing. We used Yet Another Related Posts Plugin (YARPP) which gives a list of posts or pages related to the current blog post.

The key features of this plugin are:

  • You can use thumbnail or list view for your related content.
  • It will display related posts, pages, and custom post types.
  • It has a templating system which gives you advanced control of how your results are displayed.
  • It has an advanced and versatile algorithm. This is a fully customisable algorithm which considers post titles, content, tags, categories, and custom taxonomies. A very great feature to ensure your posts are accurately related to the post.
  • It includes an option to display related posts in RSS feeds with custom display options.
  • It includes REST API support which enables you to embed related posts in your web or JavaScript-driven app!
  • It includes shortcode support. So you can simply add the [yarpp] shortcode to place related posts anywhere you like.
  • It supports HTTPS and WordPress Multisite
  • And it's a plugin that is maintained with regular updates

Sounds good right? Download YARPP.

Conclusion

We now know of two methods on how we can add Related Posts to our WordPress website. We also now know the importance of how this can improve our bounce rate. So, which method did you prefer? Let us know in the comments below!

 

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 as 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

How to Import WordPress Posts Including Images From One WordPress Site To Another

Today, we are going to show you how to import the images from WordPress posts from one website to another.

I’m sure you have tried going to Tools –> Import / Export and checking the box to include images and then you see that only the post content gets imported right?

Why the images do not get imported

The reason for this is the export step that causes issues with the image attachment. The WordPress export feature doesn’t include the ‘attachment’ post type unless you select the All content export option. If you are simply just trying to export posts from one website to another; you will lose your attachments, unfortunately.

If you do a compare from exporting just Posts and All content, the issue is quite obvious. Within the first file; in which we specified we only wanted Published statuses, the attachments are referenced in the posts, but the attachment table is ignored. In the second file, in which we exported All Statuses; the attachment table is included. In other words, the WordPress export function defines Attachment posts as something other than Published. Seems a bit of a pain but fortunately, we have a solution to the problem.

Imagine if you had a blog with 900 posts all with featured images and images within the posts and then there wasn’t a way to import this to a new site? Well, whenever there is a problem, there is always a good solution 😉

How to get your images into your new website…

Okay so if you are only wanting to import/export posts with images, then we recommend using the Auto Upload Images plugin, which can be used even to upload the images after you’ve imported the posts already.

What exactly does this plugin do?

  • It looks for image URLs in your posts (imported posts do still have image URLs in them, but they point to the site the content was exported from);
  • It then gets those external images and uploads them to the local WordPress uploads directory and adds the images to the media library;
  • And finally, it replaces the old image URLs with new URLs.

This process is easy to do and is relatively quick. Once you’ve finished the import, you can remove the plugin once the work is completed.

Step by step process

Step 1: Prepare your export file from the old website

Simply go to Tools > Export and export your posts only.

Step 2: Import your posts into your new website

On your new website, again go to Tools > Import and import the posts you exported. The importer has an option to download and import file attachments, but this won’t work if you’re not migrating all content, so you can simply ignore this option.

Step 3: Install and activate the Auto Upload Images plugin

Download the Auto Upload Images plugin and add it to your plugins folder, or simply search the name in your new website and install and activate the plugin. This will add an option under Settings > Auto Upload Images, but the default settings are all you need.

Step 4: Get the image from your old site into your new site

As of now, the plugin doesn’t have an option to automatically go through your posts and bulk upload all the images. Instead of this, it updates each post individually when you save them. If you have a lot of blog posts on your website, this can be some serious tedious work but we have a solution to that. You can go to your posts overview screen and bulk update your posts.

So what you do here is you select multiple posts and then under Bulk Actions; choose Edit and press the Apply button. Then, without making any adjustments, click the Update button. Depending on your server you may get a timeout error as the process runs, so it’s a good idea to do this maybe 20 to 50 posts at a time.

To change the Pagination, you can click Screen Options at the top right and change the default value to the value of your choice.

Step 5: Check your posts and deactivate/uninstall the plugin

When all is done you can check your posts and confirm they now reference local images. You then no longer need the plugin and you can safely deactivate and delete it.

Do note, it’s always a good idea to make a backup of your new site first (at least of your site’s database).

Alternative Solution?

The other solution is to use the Export Featured Images plugin. Although the plugin hasn’t been updated in a very long time, it still works! This will allow you to export the featured images from posts or custom post types (CPT’s) by creating a WordPress XML export including the images.

Step by step process

  • First export the posts from your old site via Tool > Export and Import the posts to your new website
  • Then use this plugin in your old site and go to Tools > Export Featured Images and select post types. This will create a new .xml file for you.
  • Now, in your new site go to Tool and select WordPress Import. Then select the .xml file which you downloaded in the previous step.

And that’s it, just as simple as that. Now you will have all your posts mapped with featured images, pretty sweet right?

If you have found this helpful, or have a different solution you would like us to mention, please leave a comment below!

Happy Coding.

 

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 as 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