php - 使用 Ajax 获取 Wordpress 帖子数据
问题描述
我在一个 WorPress 网站上工作,我希望我的页面上只有 4 个帖子,并使用 ajax 在其他帖子之间导航。
我有我的 front-page.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 );
} );
}
});
推荐阅读
- r - 如何避免在 r 中的 csv 文件中重复列名?
- spring - Spring boot 2.0.3 缺少 Spring security oauth2 'dependencies.dependency.version'
- excel - 对数组求和
- yocto - 如何将 BeagleBoneBlack 的 pasm PRU 编译器集成到 Yocto 中
- sql - 我需要 sql position() 中的文本长度
- android - HM10 与 Arduino 和 Android BLE 之间的低功耗蓝牙大数据传输
- oop - 如何使用包含 where 的抽象多方法?
- javascript - 如何使用className(javascript)在div标签上应用onclick
- reactjs - React 没有渲染任何东西?
- shell - zsh - 如何引用以多个其他变量动态命名的变量?