How to Load More Post With Ajax in WordPress

How to Load More Post With Ajax in WordPress
105 Views

Create a load more button to show additional posts or custom post types using AJAX following code in your current theme.

1. Set load more button in your post loop and pass paged parameter in post argument.

‘post’,
‘post_status’ => ‘publish’,
‘posts_per_page’ => ‘2’,
‘paged’ => 1,
);
$blog_posts = new WP_Query( $args ); ?>
have_posts() ) : ?>

have_posts() ) : $blog_posts->the_post(); ?>


max_num_pages > 1 ) : ?>
Load More

This will display two post per page.

2. Then you have to add the following code in your functions.php file.

admin_url( ‘admin-ajax.php’ ),
‘security’ => wp_create_nonce( ‘wc_load_more_posts’ ),
);
wp_localize_script( ‘custom-script’, ‘blog’, $script_data_array );
// Enqueued script with localized data.
wp_enqueue_script( ‘custom-script’ );
}

add_action(‘wp_ajax_load_posts_by_ajax’, ‘load_posts_by_ajax_callback’);
add_action(‘wp_ajax_nopriv_load_posts_by_ajax’, ‘load_posts_by_ajax_callback’);

function load_posts_by_ajax_callback() {
check_ajax_referer(‘wc_load_more_posts’, ‘security’);
$paged = $_POST[‘page’];
$args = array(
‘post_type’ => ‘post’,
‘post_status’ => ‘publish’,
‘posts_per_page’ => ‘2’,
‘paged’ => $paged,
);
$blog_posts = new WP_Query( $args ); ?>
have_posts() ) : ?>
have_posts() ) : $blog_posts->the_post(); ?>


3. Now open custom.js file and add the below code to it.

jQuery( document ).ready( function(){
var page = 2;
jQuery( function($) {
jQuery( ‘body’ ).on( ‘click’, ‘.loadmore’, function() {
var data = {
‘action’: ‘load_posts_by_ajax’,
‘page’: page,
‘security’: blog.security
};
jQuery.post( blog.ajaxurl, data, function( response ) {
if( $.trim(response) != ” ) {
jQuery( ‘.blog-posts’ ).append( response );
page++;
} else {
jQuery( ‘.loadmore’ ).hide();
jQuery( “.no-more-post” ).html( “No More Post Available” );
}
});
});
});
});

Was this article helpful?
YesNo

Leave a comment

Your email address will not be published.