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

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.

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="//"></script>

Explicit javascript code :

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

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 :

define('WP_USE_THEMES', false);
$offset = $_GET['offset'];
 $args = array(
 'numberposts' => 10,
 'order' => 'DESC',
 'offset' => $offset,
 'orderby' => 'post_date'
 $postslist = get_posts($args);
 $i = 0;
 foreach($postslist as $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>";

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.

Related Content
vps germany
Disclaimer: The content published in this article is the views of the author only. Techglimpse does not gurantee accuracy, completness or validity. If you believe the content on this post violates your copyright, please send us a mail for removal. Read more.