search ]

AJAX Load More Button for WordPress Posts

AJAX-powered “Load More” buttons are a great way to improve user experience by allowing users to load more posts dynamically without refreshing the page. This tutorial will walk you through the steps to implement a custom AJAX load more button on your WordPress site without relying on third-party plugins.

Why Use an AJAX Load More Button?

An AJAX Load More button improves site performance by loading posts dynamically as the user requests them, rather than loading all posts at once. This reduces initial page load time and allows users to control the content flow.

Might be the time to mention that there is also a post explaining How to Add Infinite Scroll to WordPress with JavaScript.

Step 1: Modify Your WordPress Query

Before we can implement the AJAX functionality, we need to modify the WordPress query to support pagination. Add the following code to your theme’s functions.php file:


function my_load_more_posts() {
    $paged = isset($_POST['page']) ? intval($_POST['page']) : 1;
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => 6, // Adjust as needed
        'paged' => $paged,
    );

    $query = new WP_Query($args);

    if ($query->have_posts()) :
        while ($query->have_posts()) : $query->the_post();
            get_template_part('template-parts/content', get_post_format()); // Adjust to your theme
        endwhile;
    endif;

    wp_reset_postdata();
    die();
}
add_action('wp_ajax_my_load_more', 'my_load_more_posts');
add_action('wp_ajax_nopriv_my_load_more', 'my_load_more_posts');

This function handles the custom query for loading more posts. It also includes actions to handle both logged-in and non-logged-in users.

Step 2: Enqueue the JavaScript

Now, we’ll enqueue the JavaScript that will trigger the AJAX call when the “Load More” button is clicked. Add this to your theme’s functions.php file:


function enqueue_load_more_script() {
    wp_enqueue_script(
        'load-more',
        get_template_directory_uri() . '/js/load-more.js',
        array('jquery'),
        null,
        true
    );

    wp_localize_script('load-more', 'load_more_params', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'current_page' => 1,
        'max_page' => $GLOBALS['wp_query']->max_num_pages,
    ));
}
add_action('wp_enqueue_scripts', 'enqueue_load_more_script');

This function enqueues the JavaScript file and passes relevant parameters such as the AJAX URL and the maximum number of pages to the script.

Step 3: Create the JavaScript File

Next, create a new file named load-more.js in your theme’s js folder. Add the following JavaScript code:


jQuery(function($) {
    var canLoadMore = true;
    var currentPage = load_more_params.current_page;
    var maxPage = load_more_params.max_page;

    $('#load-more-button').on('click', function() {
        if (currentPage < maxPage && canLoadMore) { canLoadMore = false; currentPage++; $.ajax({ url: load_more_params.ajax_url, type: 'POST', data: { action: 'my_load_more', page: currentPage }, success: function(response) { if (response) { $('.post-list').append(response); // Adjust based on your theme canLoadMore = true; if (currentPage >= maxPage) {
                            $('#load-more-button').hide(); // Hide button when no more pages
                        }
                    }
                },
                error: function() {
                    console.log('Failed to load more posts.');
                }
            });
        }
    });
});

This script triggers the AJAX request when the user clicks the “Load More” button. It increments the current page and appends new posts to the existing list.

Step 4: Add the Load More Button to Your Template

Now, you need to add the “Load More” button to your theme’s post listing template. Find the relevant file, such as index.php or archive.php, and add the button after the post loop:

<?php
echo '<div class="post-list">';
?>
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
        <?php get_template_part('template-parts/content', get_post_format()); ?>
    <?php endwhile; endif; ?>
<?php
echo '</div>';
?>
<button id="load-more-button">Load More</button>

This button will trigger the JavaScript to load more posts when clicked.

Browser Compatibility and Performance Optimization

Although this solution should work in most modern browsers, it’s a good practice to test across different browsers and devices. If performance is an issue due to multiple AJAX calls, you can optimize the scroll event using requestAnimationFrame. Here’s an example:


var ticking = false;

$('#load-more-button').on('click', function() {
    if (!ticking) {
        window.requestAnimationFrame(function() {
            // Load more logic here
            ticking = false;
        });
        ticking = true;
    }
});

This ensures that multiple AJAX calls aren’t triggered at the same time, improving performance.

Adding a Fallback for Pagination

If the “Load More” button fails for any reason, or if a user has JavaScript disabled, it’s a good idea to provide a fallback with traditional pagination links. Add the following code to your post loop template:


if (function_exists('the_posts_pagination')) {
    the_posts_pagination();
}

This ensures that users can still access additional posts through regular pagination.

SEO Considerations for AJAX Load More

While an AJAX “Load More” button improves user experience, it can complicate SEO because search engines might not be able to load content beyond the initial page. To address this, consider these tips:

  • Ensure all content is accessible via traditional pagination as a fallback.
  • Use structured data (e.g., Schema.org) to help search engines understand your content.
  • Use the rel="next" and rel="prev" attributes to indicate the sequence of paginated content.

Handling Edge Cases and Errors

It’s important to handle cases where there are no more posts to load or when an AJAX request fails. Modify the JavaScript to check if more posts are available and display a message when all posts are loaded:


if (!response || currentPage >= maxPage) {
    canLoadMore = false;
    $('#load-more-button').text('No more posts to load');
} else {
    $('.post-list').append(response);
    canLoadMore = true;
}

This ensures a smooth experience for users, even if they reach the end of the content.

Conclusion: Enhance User Experience with AJAX Load More

Implementing an AJAX “Load More” button for WordPress posts is a great way to improve user experience by providing dynamic content loading without page reloads.

This method reduces the initial load time of your site and engages users by giving them control over the content they see. Just remember to handle SEO and fallback scenarios to ensure your content is still accessible to everyone, including search engines.

Roee Yossef
Roee Yossef

I develop custom WordPress themes by design. I love typography, colors & everything between, and aim to provide high performance, seo optimized websites with a clean & semantic code.

0 Comments...

Leave a Comment

Add code using the buttons below. For example, to add PHP click the PHP button & add the code inside the shortcode. Typo? Please let us know...