使用Ajax获取Wordpress帖子数据



我在一个WorPress网站上工作,我想在我的页面上只有4个帖子,并使用ajax在其他帖子之间导航。

我有我的首页。php(简单的代码为尝试):

<section>
<button type="button" name="button" id="btn_next">+</button>
<button type="button" name="button" id="btn_pre">-</button>
<div class="" id="result"></div>
<div class="" id="offset"></div>
</section>

我有ajax。js

jQuery(document).ready(function($){
$("#btn_next").click(function(){
var off = $('#offset').html();
data_ajax(1);
})
$("#btn_pre").click(function(){
data_ajax(-1);
});
function data_ajax(new_offset){
$.ajax({
url: ajaxObject.url,
dataType: 'json',
method: 'POST',
data: {
action : 'ajax_agenda',
},
success: function(responseText){
console.log("result : " + JSON.stringify(responseText));
$("#result").html('<h3>résultats</h3>');
},
error: function(xhr, error, exception){
console.log(xhr);
console.log(error);
console.log(exception);
$("#result").html('<h3>Pas de résultats</h3>');
}
}); // fin ajax
}
});

和function.php

中的函数
add_action('wp_ajax_ajax_agenda', 'ajax_agenda');
add_action('wp_ajax_nopriv_ajax_agenda', 'ajax_agenda');
function ajax_agenda(){
$final_array = array();
$args = array(
'posts_per_page' => 3, /* how many post you need to display */
'offset' => 1,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'agenda', /* your post type name */
'post_status' => 'publish'
);
$query = new WP_Query($args);
$posts = $query->posts;
if($query->have_posts()){
$final_array["success"] = "true";
$final_array["results"] = $posts;
}
else{
$final_array["success"] = "false";
};
echo json_encode( $final_array );

die(); // Pour eviter les erreurs due au "die(0)"" prédrnt dans le fichier "admin-ajax.php"
};

但我没有到达使用数据返回的js:(我需要你的帮助。

PHP代码
function get_ajax_posts_data() {
$args = array(
'post_type' => array('yout post type'),
'post_status' => array('publish'),
'posts_per_page' => 10,
'order' => 'DESC',
'orderby' => 'date',
);
$ajaxposts = get_posts( $args );
echo json_encode( $ajaxposts );
}
add_action('wp_ajax_get_ajax_posts_data', 'get_ajax_posts_data');
add_action('wp_ajax_nopriv_get_ajax_posts_data', 'get_ajax_posts_data');

jQuery代码:


$.ajax({
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php');?>',
dataType: "json",
data: { action : 'get_ajax_posts_data' },
success: function( response ) {
$.each( response, function( key, value ) {
console.log( key, value ); 
} );
}
});

最新更新