Blog

Uncategorized WordPress load more posts using ajax

Hi guys this is new post for WordPress series, From this post i am going elaborate a interesting topic that How to show WordPress posts or custom post type’s post with load more button.

This is very fancy and advanced way to show your WordPress posts without pagination and page refresh.

And also this is very handy to use in particular section of div like you can use in one page website or wherever you want.

So we can achieve this task using HTML in template page and j Query and functions.php page.
Please see the Working Example .

So now we first write html code where we fetch WordPress posts using ajax.

Now very firstly i created a  div structure of html.I created result container that will contain all appended dynamic posts and there is one more div that contain button of load more.
Okay copy this code and put this code where you want to show.

<div class="result_data inerresult_data clearfix" id="results">	
</div>		
 <div align="center"  class="centerbtn">	 
        <button id="load_more_button"><img src="http://nrtechwebsolution.com/wp-content/themes/wpex-adapt/images/ajax-loader.gif"  class="animation_image" style="float:left; max-width: 17px;"> Load More</button> 
 </div>

Our div container is ready to use so now we have to create some java script functions that will handle ajax request on button click.
You can copy this code into your js file and include into page where you want use in word press.

< script>
 jQuery(function($){
	
	if($("#load_more_button").length > 0){
		
		var track_page = 1; 
		/* //track user click as page number, righ now page number 1 */
		load_contents(track_page);
		$("#load_more_button").click(function (e) { 
		/* //user clicks on button
			 //page number increment everytime user clicks load button */
			 track_page++;
			 console.log(track_page);
			load_contents(track_page); 
			/* //load content */	
		});

		$('#advance_search').on('submit',function(){
			formData = $(this).serialize();
			track_page=1;
			$("#results").html('');

		/* 	//append data into #results element */

			load_contents(track_page);
			return false;
		});
			
		/* //Ajax load function
		 */
		function load_contents(track_page1){
			$('.animation_image').show();
			
			/* //show loading image */
			
			$.post( ajaxurl, {'p': track_page1,'action':'grab_posts'}, function(data){
				
				if(data == 300){
					
					/* //display text and disable load button if nothing to load */
					
					$("#load_more_button").text("You have reached end of the record!").prop("disabled", true);
				}
				
				/* // window.location.hash = '#'+track_page1; */
			   if(data != 300){
				$("#results").append(data);
			   }
				
				/* //append data into #results element */
				
				$("#load_more_button").offset().top
				
				/* hide loading image */
				$('.animation_image').hide();
				/* //hide loading image once data is received */
			});
		}

	}
});

</script>

Java script functions are ready to call server request to fetch posts records from MySQL table but her i am using word press MySQL table so i use WP_Query method that will return posts.
So please note there is a “post_type” in args array variable.So i use “demo” that is custom post type you can choose your custom post type like (page,post,property,listing.. etc).
Now its time to copy php code into your functions.php

<php 
add_action( 'wp_ajax_grab_posts', 'grab_posts' );
add_action( 'wp_ajax_nopriv_grab_posts', 'grab_posts' );

function grab_posts(){
	$number=5;
	$paged = isset($_REQUEST['p']) ? $_REQUEST['p'] : 1;
	$offset = ($paged - 1) * $number;
	$args = array(
		'post_type' => 'demo',
		'post_status'=>'publish',
		'posts_per_page' => $number ,
		 'paged' => $paged,
		'offset' => $offset,
	 );
     $post_query = new WP_Query( $args );	
		
  if ( $post_query->have_posts() ) { 
		while ( $post_query->have_posts() ) { 
			$post_query->the_post();
	
		 $post_img ='';
		if ( has_post_thumbnail() ) {
		       $post_img = wp_get_attachment_url( get_post_thumbnail_id() );
           }
		   $author = get_the_author();
   ?>

		 <article class="loop-entry clearfix">
				<h2><a href="#" title="Ajax based registration in wordpress"><?php the_title(); ?></a></h2>
				<ul class="loop-entry-meta">
					<li class="loop-entry-meta-date"><i class="fa fa-clock-o"></i>On <?php the_date('Y-m-d'); ?></li>
					<li class="loop-entry-meta-author"><i class="fa fa-user"></i>By <a href="#" title="Posts by admin" rel="author"><?php echo  $author; ?></a></li>
									
				</ul><!-- /loop-entry-meta -->
					 <?php the_excerpt(); ?>

	     </article>
		      
	<?php
			}
			} else {
				echo 300; 
				}
	die;

	
}


/* add ajax url for wordpress in head section*/
 add_action('wp_head','loadscriptfnc');
 function loadscriptfnc(){
	 
	 echo '<script>var ajaxurl="'.admin_url('admin-ajax.php').'"; </script>';
 }
	?>

Author Details