AJAX (Asynchronous JavaScript and XML) is a web technology that allows a web page to dynamically update content without reloading the page within the browser. The website becomes more interactive and responsive with the use of this technology. WordPress pagination with AJAX is important topic nowadays. Because every website wants to load its content asynchronously so that page loads with speed.
By using little bit jQuery/JavaScript, we can easily make our WordPress paginated content load using AJAX. In this post, we are taking paging only using simple previous and next post navigation. We should go like this…
WordPress pagination with AJAX
The layout of content inner div looks like:
1 2 3 4 5 | <div id='content'> <div id='contentInner'> All the Posts & navigations are located here </div> </div> |
Pagination HTML would be like this..
1 2 3 4 | <ul id='Pagination'> <li>< ?php previous_posts_link('« PREV') ?></li> <li>< ?php next_posts_link('NEXT »') ?></li> </ul> |
NOTE : Pagination HTML should be in ‘contentInner‘ div.
Here WordPress function previous_posts_link and next_posts_link both create the links of previous and next page for the posts. Now we will call the click event of these links using jQuery..
1 2 3 4 5 6 7 8 9 10 11 12 | <script type="text/javascript"> jQuery(document).ready(function(){ jQuery(document).on('click','#Pagination a', function(e){ e.preventDefault(); var link = jQuery(this).attr('href'); jQuery('#ID').html('Loading...'); jQuery('#ID').load(link+' #contentInner'); }); }); </script> |
Here we are binding pagination click event using ‘on‘ due to dynamically loading content because next/prev post page will be loaded with paging navigation.
Change the #ID with the ID of the div wrapping the #contentInner div of your page (the div holding your content) and add the code in the footer.php or header.php file of the current theme.
Here before loading the content, we are giving the message of ‘Loading…’ that can be changed according to our need like loading image with img tag.
Using Ajax we can make our site more interactive and user friendly. Its highly recommendable to use Ajax while developing our website.
Hi,
try my code: https://gist.github.com/Studioartcz/5241030b656c9f25f565