How to get wordpress custom post data in json?

时光怂恿深爱的人放手 提交于 2019-12-08 07:09:07

问题


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

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.

回答1:


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);
			
		}
				
	});	
	
});	


来源:https://stackoverflow.com/questions/46722405/how-to-get-wordpress-custom-post-data-in-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!