Search code examples
wordpresswordpress-themingcustom-wordpress-pages

How to get wordpress custom post data in json?


In my template file i fetch the custom post data like this ,

enter image description here

Initially I fetch 7 post, I need to make a read more button bellow the post, which will fetch more 7 posts from the wp database table, when someone click on it.

But I don't know how to do it, I want to know about,

  • In jquery get method, which php file i call for the data,
  • How or what exact script i will write in that php file.

Solution

  • Here i have added a rough idea how you can write your code :

    Create a ajax function in function.php , and pass offset value to it through ajax call and just append the received data in your disply section.

    here is an example of creating ajax function :

    add_action('wp_ajax_nopriv_cyt_ajax_search','cyt_ajax_search');
    add_action('wp_ajax_cyt_ajax_search','cyt_ajax_search');
    function cyt_ajax_search(){
    
    
        $offset = $_POST['offset'];
    
        $args = array (
        'post_type' => 'post',
        'posts_per_page' =>7
        'offset'=>$offset,
    
        'meta_query' =>..........
    
        );
    $query = new WP_Query($args);
    if($query->have_posts() ) : 
            while ( $query->have_posts() ) : $query->the_post(); 
    
    
    endwhile; 
    
    wp_reset_postdata();
    endif; 
    
    
    }
    

    //Frontend code , on button click it will cal the ajax function and pass the offset value, on each click you need to increase the value by 7 (in case you want to load 7 post only ) and check how many post are left and if offset value exceedded the no of total counted data to be display by wp query then simply hide the button

    <div id ="esiSection"></div>
    
    <span click="loadmore" data-offset='0'>Click here</span>  
    
    jQuery('.loadmore').click(function(){ 
    var offset = parseInt(jQuery(this).attr('data-offset'));
    jQuery.ajax({				
    			url: '<?php echo admin_url('admin-ajax.php'); ?>',
    			type: 'POST',			 
    			data: { 
    				'action' : 'cyt_ajax_search',  
    				'offset' : offset ,
    			},
    		success: function(response) {
    		
    			jQuery('#resiSection').append(response);
    			offset = offset + 7;
    	
    			
    		},
    		error: function(error){
    			console.log(error);
    			
    		}
    				
    	});	
    	
    });