WordPress ajax next previous button without plugin

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">
	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) {
		print "<li>";
		print "<a href=".esc_url( get_permalink() ).">";
		print "<h4>".substr(get_the_title(), 0, 50)."</h4>";
		print "<p>".substr(get_the_excerpt(),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.

add a comment

Leave a Reply

Your email address will not be published. Required fields are marked *