Load the next page using ajax

Last modified September 24, 2019
.* :☆゚

If you want to dynamically load the next page on a WordPress site without a hard page refresh, you really don’t need a whole extra plugin. Best of all, it’s quite quick and easy to implement thanks to JQuery and WordPress’ awesome post functionality.

1. Match your loop markup to the snippet below, using the same classes and markup.

<div class="posts">
  <?php if (have_posts()) : ?>
    <?php while (have_posts()) : the_post(); ?>

      <div class="entry-content">
        <?php the_content('Read the rest of this entry »'); ?>

    <?php endwhile; ?>

    <div class="posts-navigation">
      <?php next_posts_link( 'Load More' ); ?>

    <?php else : ?>
    <?php get_template_part( 'template-parts/content', 'none' )
  <?php endif;?>

2. In your scripts, paste the following snippet and check all classes and wrappers match your markup.

//paste this wherever you are loading your JavaScript from
  $('body').on('click', '.posts-navigation a', function (e) {

    let $page = $(this).attr('href');


    //update the button so the user knows something is happening

    $.get($page, function (data) {
      //filter the received data and store the required vars
      let $items = $(data).find('.entry-content'),
          $nextpage = $(data).find('.posts-navigation a').attr('href'),
          $container = $('.posts');

      //append the new posts to the posts wrapper

      //now we can update the button so it's ready for the next batch of posts, and at the same time check if there is another link to the next page
      $('.posts-navigation a').text('Load More').attr('href', $nextpage);

      //check if there are no more posts to load by looking for the href in the received data
      //if there is no next page link, it will be undefined. hence, we can then hide the pagination button (or remove() if you wish).
      if ($nextpage === undefined) {
        $('.posts-navigation a').hide();

  • set the number of posts per page in your Reading settings or pre_get_posts.
  • you can use this same method for any kind of WordPress loop, since it relies on GET and is essentially loading the next page, filtered.
  • this method is great if you just want to load the next page dynamically, however if you want to modify the query when you click on ‘Load More’ you’ll need to use the POST method instead (a story for another day).