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">
$(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);
		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>";
		$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.

add a comment

Leave a Reply

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

*