WordPress: Load More Posts Using AJAX On Button Click
AJAX load always makes the website look fancy and cool in a way that a user does not have to reload the webpage to view more contents. Not only this but using AJAX for loading contents or part of webpage significantly increases the performance and reduces bandwidth usage. Reloading the whole page just to view few more post is not that a good thing. Instead loading only the needed content and displaying to user without having to reload the whole page is far more better in terms of both user experience and server load.
So, in this article I will show you how you can implement ajax loading on button on wordpress website without using a plugin. I am considering that you know the basic file structure and working of files like function.php
, index.php
on WordPress.
Load More Posts On WordPress Using AJAX Without Using Plugin
First of all, let’s talk about what we need. We need a js file for sending ajax request and some rest api functions to handle that request. First, let’s enqueue a js file into our project. Paste the following code at the end of your functions.php
function bsubash_load_more_scripts() {
wp_enqueue_script('jquery');
wp_register_script( 'loadmore_script', get_stylesheet_directory_uri() . '/js/ajax.js', array('jquery') );
wp_localize_script( 'loadmore_script', 'loadmore_params', array(
'ajaxurl' => admin_url('admin-ajax.php'),
) );
wp_enqueue_script( 'loadmore_script' );
}
add_action( 'wp_enqueue_scripts','bsubash_load_more_scripts' );
Here, the js file we just enqueue has to be placed inside js
folder of your root theme directory. We have also localized the script so that we can use the php
variables in that js
file.
Now, let’s create a AJAX Handler. Paste the following code at the end of functions.php
file.
function bsubash_loadmore_ajax_handler(){
$type = $_POST['type'];
$category = isset($_POST['category']) ? $_POST['category']: '';
$args['paged'] = $_POST['page'] + 1;
$args['post_status'] = 'publish';
$args['posts_per_page'] = $_POST['limit'];
if($type == 'archive'){
$args['category_name'] = $category;
}
query_posts( $args );
if( have_posts() ) :
while(have_posts()): the_post();
//write your single post card
the_title();
the_excerpt();
endwhile;
endif;
die;
}
add_action('wp_ajax_loadmore','bsubash_loadmore_ajax_handler');
add_action('wp_ajax_nopriv_loadmore','bsubash_loadmore_ajax_handler');
We have now done the back-end part. Let’s see an example of displaying posts.
<div class="latest_posts_wrapper">
<?php
$paged = ( get_query_var('page') ) ? get_query_var('page') : 1;
$latests = new WP_Query(array(
'post_type' => 'post',
'posts_per_page' => 3,
'paged' => $paged
));
while($latests->have_posts()): $latests->the_post();
//put the post card here
the_title();
the_excerpt
endwhile;
?>
</div>
<script>
var limit = 3,
page = 1,
type = 'latest',
category = '',
max_pages_latest = <?php echo $latests->max_num_pages ?>
</script>
<?php if ( $latests->max_num_pages > 1 ){
echo '<div class="load_more text-center">
<a href="#" class="btn btn-circle btn-inverse btn-load-more">More Article</a>
</div>';
}else{?>
<article>
<h1>Sorry...</h1>
<p><?php _e('Sorry, No Posts Available !'); ?></p>
</article>
<?php }
wp_reset_query();
?>
This will query the posts initially, display some and set required variables for AJAX request. Initially, the page is set to 1 and you can modify other variables like limit etc as per your need. The load more button will only be displayed when the current page is not last page and there are more posts that can be displayed.
Let’s see the final section of this article, The AJAX request. Paste the following code inside theme_directory/js/ajax.js
.
jQuery(function($) {
$('.btn-load-more').click(function(e) {
e.preventDefault();
var button = $(this),
data = {
'action': 'loadmore',
'limit': limit,
'page': page,
'type': type,
'category': category
};
$.ajax({
url: loadmore_params.ajaxurl,
data: data,
type: 'POST',
beforeSend: function(xhr) {
button.text('Loading...'); // change the button text, you can also add a preloader image
},
success: function(data) {
if (data) {
$(".latest_posts_wrapper").append(data);
page++;
button.text('More Articles');
if (page == max_pages_latest)
button.remove(); // if last page, remove the button
} else {
button.remove(); // if no data, remove the button as well
}
}
});
});
});
That’s it. You are now all set to use AJAX loading on your website. You can modify the code as per your need. If you feel any trouble implementing, feel free to leave a comment below.