How to Load More Post With Ajax in WordPress

How to Load More Post With Ajax in WordPress
272 Views

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

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

<div class="cxc-post-wrapper">
	<div id="cxc-posts" class="cxc-posts">
		<?php
		$postsPerPage = 3;

		$args = array(
			'post_type' => 'post',
			'post_status' => 'publish',
			'posts_per_page' => $postsPerPage,
		);

		$the_query = new WP_Query( $args );

		if ( $the_query->have_posts() ) {
			while ( $the_query->have_posts() ){ 
				$the_query->the_post();
				?>

				<div class="cxc-inner-wrapper">
					<h1><?php the_title(); ?></h1>
					<p><?php the_content(); ?></p>
				</div>

				<?php
			}
		}
		wp_reset_postdata();
		?>
	</div>
	<button type="button" id="codex-load-more" class="codex-load-more" data-page="2">Load More</button>
</div>

This will display two post per page.

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

<?php
add_action( 'wp_enqueue_scripts', 'cxc_theme_enqueue_script_style' );

function cxc_theme_enqueue_script_style() {

	wp_enqueue_script( 'custom-script', get_template_directory_uri(). '/assets/js/custom.js', array('jquery') );
	// Localize the script with new data
	wp_localize_script( 'custom-script', 'ajax_posts', array(
		'ajaxurl' => admin_url( 'admin-ajax.php' ),
		'noposts' => __( 'No older posts found', 'cxc-codexcoach' ),
	));

}

add_action( 'wp_ajax_nopriv_codex_load_more_post_ajax', 'codex_load_more_post_ajax_call_back' );
add_action( 'wp_ajax_codex_load_more_post_ajax', 'codex_load_more_post_ajax_call_back' );

function codex_load_more_post_ajax_call_back(){

	$posts_per_page = ( isset( $_POST["posts_per_page"] ) ) ? $_POST["posts_per_page"] : 3;
	$page = ( isset( $_POST['pageNumber'] ) ) ? $_POST['pageNumber'] : 1;

	$args = array(
		'post_type' => 'post',
		'posts_per_page' => $posts_per_page,
		'post_status' => 'publish', 
		'paged'    => $page,
	);

	$the_query = new WP_Query( $args );

	$html = '';
	ob_start();

	if ( $the_query->have_posts() ) {
		while ( $the_query->have_posts()) { $the_query->the_post();
			?>
			<div class="cxc-inner-wrapper">
				<h1><?php echo get_the_title(); ?></h1>
				<p><?php echo get_the_content(); ?></p>
			</div>
			<?php
		}
	} 

	wp_reset_postdata();
	$html .= ob_get_clean();

	wp_send_json( array( 'html' => $html ) );
}
?>

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

jQuery( document ).ready( function($){

	var posts_per_page = 3; 

	function cxc_load_more_posts( cxc_this, pageNumber ){
		var page_count = 0;
		var str = '&pageNumber=' + pageNumber + '&posts_per_page=' + posts_per_page + '&action=codex_load_more_post_ajax';

		if( !cxc_this.hasClass('cxc-disabled') ) {

			jQuery.ajax({
				type: "POST",
				dataType: "html",
				url: ajax_posts.ajaxurl,
				data: str,
				success: function(response){
					if( response ){
						cxc_this.removeClass('cxc-active');
						var json_html = JSON.parse(response); 
						if( json_html.html.length ){
							page_count = parseInt(pageNumber) + parseInt(1);
							cxc_this.attr('data-page', page_count);
							cxc_this.parents('.cxc-post-wrapper').find(".cxc-posts").append(json_html.html);
						} else {
							cxc_this.attr("disabled",true);
							cxc_this.addClass('cxc-disabled');
						}
					}
				}
			});
		}
		return false;
	}

	jQuery(document).on("click",".codex-load-more",function(){ 
		var cxc_this = jQuery(this);
		var paged = cxc_this.attr('data-page');	
		cxc_this.addClass('cxc-active');
		cxc_load_more_posts( cxc_this, paged );
		cxc_this.insertAfter('.cxc-posts'); // Move the 'Load More' button to the end of the the newly added posts.
	});

});
Was this article helpful?
YesNo

Leave a comment

Your email address will not be published.