Ajax Load More Posts Instead of Pagination

Ajax load more feature allows users to dynamically load additional posts without reloading the entire page. By using Ajax, you can create a seamless browsing experience for visitors, especially on content-heavy websites.

Replacing traditional pagination with Ajax load more functionality not only improves the user experience but also reduces the load time and server resources required to fetch and display content. This results in faster page loading times and a more engaging browsing experience for your audience.

This tutorial will guide you through implementing Ajax load more functionality in WordPress.

Detailed Guide:

1. Display the Posts and Load More Button:

You can use this code in the following theme files:

  • index.php: To display posts on the main blog page.
  • archive.php: To show posts on archive pages (category, tag, date, author, etc.).
  • search.php: To display search results.
  • home.php: For the main blog page if index.php is not present.
  • page.php: If you want to display posts on a static page.
  • single.php: To show posts when viewed individually.
  • Custom template files created within your theme.
<div id="posts_list">
	<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
		<div class="post">
			<?php the_title(); ?>
			<?php the_excerpt(); ?>
		</div>
	<?php endwhile; else: echo '<p>'.__('No content.', 'text-domain').'</p>'; endif; ?>
</div>
<?php 
$load_more_btn = (get_query_var('paged') < $wp_query->max_num_pages) 
    ? '<div class="load-more-btn"><a href="#" id="load-more-posts">Load More</a></div>' 
    : 'none';
echo $load_more_btn;
?>
  • Following the post display section, a condition based on the current pagination page is checked. If the current page is less than the total number of pages ($wp_query->max_num_pages), a <div> element with the class load-more-btn containing a “Load More” link with the id load-more-posts is generated.
  • Conversely, if the condition is not met, “none” is displayed instead of the “Load More” button.
  • Lastly, the code concludes by outputting the created “Load More” button block or “none” based on the pagination condition.

Make sure to integrate the code into the appropriate template file based on where you want the posts and “Load More” button to appear within your WordPress theme.

2. Register Scripts and Handle Ajax Requests:

This code, which handles Ajax post loading and registers scripts, should be added to the functions.php file of your WordPress theme.

function loadmoreposts_scripts() {
    wp_enqueue_script('loadmoreposts', get_template_directory_uri() . '/js/loadmoreposts.js', array('jquery'), '1.0', true);
    
    global $wp_query;
    $total_pages = $wp_query->max_num_pages;
    
    wp_localize_script('loadmoreposts', 'loadmore_params', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'total_pages' => $total_pages,
    ));
}
add_action('wp_enqueue_scripts', 'loadmoreposts_scripts');

function load_more_posts() {
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => get_option('posts_per_page'),
        'paged' => $_POST['page'],
    );
    $query = new WP_Query($args);

    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
            echo '<div class="post">';
            the_title();
            the_excerpt();
            echo '</div>';
        }
    }
    wp_die();
}
add_action('wp_ajax_load_more_posts', 'load_more_posts');
add_action('wp_ajax_nopriv_load_more_posts', 'load_more_posts');
  • The loadmoreposts_scripts() function is responsible for enqueueing the loadmoreposts.js script with jQuery as a dependency. It also localizes the script by passing data like ajax_url and total_pages to be used in the script.
  • Within loadmoreposts_scripts(), the total number of pages in the current query is determined using $wp_query->max_num_pages.
  • The localized data is passed to the script using wp_localize_script(), which makes the variables accessible in the loadmoreposts.js script.
  • The load_more_posts() function is an Ajax handler that processes the request to load more posts based on the page number sent via $_POST['page'].
  • Inside load_more_posts(), a new WP_Query is created with parameters to fetch the next set of posts based on the page number received from the Ajax request.
  • The function then loops through the queried posts using while loop and outputs each post’s title and excerpt wrapped in a <div> element with the class post.
  • Once all posts are processed, wp_die() is called to end the script and prevent any additional output.
  • Two action hooks wp_ajax_load_more_posts and wp_ajax_nopriv_load_more_posts are used to handle the Ajax request for authenticated and non-authenticated users, respectively, by associating them with the load_more_posts() function.

3. JavaScript Code:

To implement the described JavaScript functionality, you need to create a file named loadmoreposts.js within your theme directory (usually in a subfolder like /js/).

Copy the JavaScript code snippet provided above into the loadmoreposts.js file.

jQuery(function($) {
    var page = 1;
    var totalPages = loadmore_params.total_pages;

    $('#load-more-posts').on('click', function(e) {
        e.preventDefault();
        var $btn = $(this);

        $.ajax({
            url: loadmore_params.ajax_url,
            type: 'POST',
            data: {
                action: 'load_more_posts',
                page: page,
            },
            success: function(response) {
                $('#posts_list').append(response);
                page++;

                if (page > totalPages) {
                    $btn.hide();
                }
            },
            error: function(xhr, status, error) {
                console.log(error);
            }
        });
    });
});
  • The JavaScript code in loadmoreposts.js aims to handle the Ajax functionality for loading more posts without refreshing the page.
  • The script begins by encapsulating its code within a jQuery document-ready function to ensure that the code executes when the DOM is fully loaded.
  • It initializes variables page and totalPages to keep track of the current page number and the total number of pages available for post pagination.
  • An event listener is set up to listen for clicks on the “Load More” button with the id load-more-posts.
  • When the button is clicked, an Ajax request is made to retrieve additional posts. The request includes the current page number in the data payload.
  • Upon successful completion of the Ajax request, the response containing the additional post content is appended to the #posts_list element, displaying them on the page.
  • The script increments the page variable to prepare for loading more posts on subsequent clicks, and it checks if the current page exceeds the total available pages to hide the “Load More” button when all posts have been loaded.
  • In case of any errors during the Ajax request, the script logs the error in the browser console for debugging purposes.
  • The script enhances user experience by enabling dynamic loading of posts and providing a seamless browsing experience without the need to navigate to separate pages for more content.

By following this tutorial, you can seamlessly implement Ajax load more functionality for WordPress posts. This technique improves user engagement and provides a modern browsing experience. Upgrade your website with Ajax load more feature today!