How to dynamically load contents on previous and next navigation buttons click using Ajax

Updated on September 19, 2017

In continuation to my previous posts “How to use WordPress functions/posts outside the WordPress directory“, here i will be showing you how to load more contents from WordPress using Ajax on previous and next navigation buttons. Like garnishing on food for attractive look, i have shown the contents on post-it in Live Demo.

Demo

ajax-loading content using prev and next navigation buttons
ajax-loading content using prev and next navigation buttons

Create an index.html file :

Include jQuery and respective css file in thesection of your html template.

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

Explicit javascript code :

<script type="text/javascript">
$(document).ready(function(){
 var offset=0;
 loadCurrentPage();
 $("#next, #prev").click(function(){
 offset = ($(this).attr('id')=='next') ? offset + 10 : offset - 10;
 if (offset<0)
 offset=0;
 else
 loadCurrentPage();
 });
 function loadCurrentPage(){
 $.ajax({
 url: 'posts.php?offset=' + offset ,
 type: 'POST',
 cache: true,
 success: function (data) {
 $('#displayResults').html(data);
 }
 });
 }
});
</script>

In the above javascript code, we are loading the initial contents(10 posts) first using loadCurrentPage() function. Then once the prev or next button is clicked, we increment the offset number by 10 (for getting next 10 posts). The contents are retrieved from serverside posts.php. Below is the prev and navigation buttons.

<div id="prev" class="large magenta awesome">‹ Prev</div>
<div id="next" class="large magenta awesome">Next ›</div>

Below is the div in which you load your contents.

<div id="displayResults"></div>

Create a posts.php file :

<?php
define('WP_USE_THEMES', false);
require_once('../wp-load.php');
$offset = $_GET['offset'];
?>
<ul>
<?php
 $args = array(
 'numberposts' => 10,
 'order' => 'DESC',
 'offset' => $offset,
 'orderby' => 'post_date'
 );
 $postslist = get_posts($args);
 $i = 0;
 foreach($postslist as $post) {
 setup_postdata($post);
 $the_content = get_the_excerpt();
 $the_title = get_the_title();
 $the_link = get_permalink();
 print "<li>";
 print "<a href=" . $the_link . ">";
 print "<h4>" . substr($the_title, 0, 50) . "</h4>";
 print "<p>" . substr($the_content,0, 100) . "....</p>";
 print "</a>";
 print "</li>";
 $i++;
 }
?>
</ul>

Every time next button is pressed, you increment the offset by 10 and send as an argument to posts.php. In the posts.php, use this offset and get the next 10 posts and list. See the below live demo and you can download the script to try yourself. For the download to work, you need to put posts.php script into your PHP server and proper path for WordPress need to be included in that file.

Checkout Demo here

Was this article helpful?

Related Articles

Comments Leave a Comment

Leave a Comment