-1

how could I add load more posts to my theme? Is it possible to add it without using rest api?

1

1 Answer 1

2

You can add a load more button using a variety of WordPress plugins, just pick one and follow the instructions. I like this one: https://wordpress.org/plugins/ajax-load-more-anything/

Yes, it is possible to add it without using the REST API but the REST API is a great use for this type of activity. To provide a concrete example I would need to see the exact page you are working on but the basic approach (NOT using the REST API) is as follows: Add some jQuery code to every page that:

  1. interrupts the click event
  2. calls the page via Ajax
  3. parses out the additional posts
  4. appends the posts to the end of the current list

So, given the following HTML:

<section id="blogposts">
  <article>(blog post HTML)</article>
</section>
<a id="loadmore" href="(href to next page of results)">Load More</a>

You might have jQuery that looks kind of like this (kind of because there are a lot more details you'll need to manage to make this bullet proof - this example just loads the next page of posts):

$("#loadmore").on("click", function(e){
  e.preventDefault
  var nextPage;
  $.ajax({
      type: 'GET',
      url: nextPage.attr('href'),
      success: function(data) {
          if (0 == data.length) {
              // nothing more to show
          } else {
              var frag = $.parseHTML(data)).children('#blogposts');
              $('#blogposts').append($(frag));
          }
      },
      error: function(data) {
          nextPage.text('Error loading more… Click to try again');
      }
  });
});

The above script isn't perfect but should give you an idea how this can be done without using the REST API.

Not the answer you're looking for? Browse other questions tagged or ask your own question.