Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Get category and their post via ajax

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 2.12k
    Comment on it

    Hello readers, today I guide you "How to get category and their post via ajax".

    Suppose we have 5 category in Wordpress and we want to display it in tab base and also display their post. In first when our page is loaded, 2 post are shown for each category and below a button will appear "Load More". If you click "Load More" button other post will append in the last of the current post shown in the current view-port.

    For doing this you can create a php file like "ajax-quectiondata.php" into your theme folder.

    Now use my below code and put it into your page where you want to display all category and their related post.

     

    <!-- Nav tabs -->
    <ul class="nav nav-tabs col-md-4 col-sm-4 col-xs-12" role="tablist">
    	<?php
    	$taxonomy = 'question-category';
    	$terms = get_terms( $taxonomy, array(
    		'order'  	 => 'ASC',
    		'hide_empty' => true
    	));
        $i=1;
        foreach ($terms as $term) {
    ?>
    	<li role="presentation" class="<?php echo ( $i == 1 ) ? 'active' : '';?> ">
    		<a class="categoryID" href="#home_<?php echo $term->term_id;?>" data-name="<?php echo $term->slug;?>" data-seq="<?php echo $term->term_id;?>" data-set="<?php echo $term->count;?>" aria-controls="home_<?php echo $term->term_id;?>" role="tab" data-toggle="tab"><?=$term->name;?></a>
    	</li>
    <?php
    	$i++;
    	}
    ?>
    </ul>
    			  <!-- Tab panes -->
    			
    <div class="tab-content col-md-8 col-sm-8 col-xs-12 rightSection">
    	<?php
    		
    		$taxonomys = 'question-category';
    	$termss = get_terms( $taxonomys, array('hide_empty' => false));
    	$j=1;
    	foreach ($termss as $tem)
    	{
    		if($j==1){$set_id=$tem->term_id;$set_slug=$tem->slug;}
    		$args = array(
    		'post_type'              => array( 'question' ),
    		'post_status'            => array( 'publish' ),
    		'posts_per_page'         => 2,
    		'tax_query' => array(
    		    array(
    		    'taxonomy' => 'question-category',
    		    'terms' => $tem->term_id
    		     )
    		  )
    		);
    
    		$active = ($j==1) ? 'active' : ''; 
    		echo "<div role='tabpanel' class='tab-pane post-".$tem->slug." ".$active."' id='home_".$tem->term_id."'>";
    		$query = new WP_Query( $args );
    		if ( $query->have_posts() ) {
    			while ( $query->have_posts() ) {
    				$query->the_post();
    	?>
    		<p class="subheading"><?php the_title();?></p>
    		<p class="text"><?php the_content();?></p>
        <?php
        	$j++;
    		    }
    		}
    		echo "<p class='text-center' id='cat-".$tem->slug."'><button data-total-record='".$tem->count."' data-total-shown='2' class='talkBtn' data-set='".$tem->count."' id='".$tem->slug."' data-name='' onclick='get_posts(this)'>Load More...</button></p>";
    		echo "</div>";
    	}
    	wp_reset_postdata();
    	
    ?>
     	</div><!-- rightsection -->
    	<div class="clear"></div>
    	<input type="hidden" name="hidecatid" id="hidecatid" value="<?php echo $set_id;?>">
    </div><!-- tabs -->

     

    Now, copy the below code and put it into your "ajax-quectiondata.php" file.

     

    <?php
    	require_once('../../../wp-config.php');
    	global $wpdb;
    
    	//print_r($_GET);exit;
    	$id = $_GET['cat_id'];
    	$offset = $_GET['offset'];
    	//echo $id;
    
    	$args = array(
    		'post_type'              => array( 'question' ),
    		'post_status'            => array( 'publish' ),
    		'offset'           		 => $offset,
    		'posts_per_page'         => 1,
    		'tax_query' => array(
    		    array(
    		    'taxonomy' => 'question-category',
    		    'terms' => $id
    		     )
    		  )
    		);
    		$query = new WP_Query( $args );
    		$j=1;
    		$data = array();
    		if ( $query->have_posts() ) {
    			while ( $query->have_posts() ) {
    				$query->the_post();
    
    				$data[$j]['post_title'] = get_the_title();
    				$data[$j]['post_content'] = get_the_content();
    	    	$j++;
    			    }
    			    
    			}
    
    			echo json_encode($data);
    			die();
    			

     

    Last step, add the below script into your footer page.

     

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
    <script type="text/javascript">
    	// facts page
    	$(document).ready(function() {
    		$('.categoryID').click(function(){
    			var idCat = $(this).data('seq');
    			var catslug = $(this).data('name');
    			//$( ".talkBtn" ).attr("data-name", catslug );
    			$('#hidecatid').val(idCat);
    		});
    	});
    
    	// end facts page
    	function get_posts(obj){
    		var setData = $(obj).attr("id"); // get data-name attribute on click Load More button
    		var count_post = $(obj).data('set');// get total number of post in a current category
    		var before_append_post = $('.post-'+setData+' p.subheading').length; // check number of post show before append
    
    		if( count_post == before_append_post ) {
    			$('#'+setData).remove();
    		}
    
    		var cat_id = $('#hidecatid').val(); // get category id
    
    		var myData = {};
    		myData.offset = $(obj).data('totalShown');
    		myData.cat_id = cat_id;
    		$.ajax({
    			url: "<?php echo get_bloginfo( 'template_url' ); ?>/ajax-quectiondata.php",
    			data: myData,
    			dataType: 'json',
    			success: function(responseData) {
    					
    		        $.each(responseData, function(i, item) {
    		            //alert(item.post_title);
    		            var pre_post  = $('.post-'+setData).children('p.subheading').last().text();
    					if(item.post_title != pre_post){
    						$('#cat-'+setData).before( "<p class='subheading'>"+item.post_title+"</p>");
    						$('#cat-'+setData).before( "<p class='text'>"+item.post_content+"</p>");
    					}
    		        });
    		        //alert((myData.offset+1));
    		        $(obj).data('totalShown', (myData.offset+1));
    		        //alert($(obj).data('totalShown'));
    				
    				var after_append_post = $('.post-'+setData+' p.subheading').length; // check number of post show after append 
    				if( count_post == after_append_post ) {
    					$('#'+setData).remove();
    				}
    			}
    		});
    	}
    </script>

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: