我正在尝试在我的 Wordpress 应用程序中构建一个“加载更多”按钮,但 AJAX 返回值始终为“成功:false”,即使我知道数据库中还有更多帖子。我遵循了在 YouTube 上找到的教程,但不确定我遗漏了什么。
JS
jQuery(document).ready(function () {
const button = document.getElementById('loadmore');
button.addEventListener('click', () => {
let current_page = document.querySelector('#main-content').dataset.page;
// let max_pages = document.querySelector('#main-content').dataset.max;
const params = {
'action': 'load_more_posts',
'current_page': current_page
}
$.post('/wp-admin/admin-ajax.php', params, (data) => {
console.log(data);
});
});
})
PHP (函数.php)
wp_enqueue_script('loadmore', get_template_directory_uri() . '/js/loadmore.js', array('jquery'), filemtime(get_template_directory() . '/js/loadmore.js'));
add_action('wp_ajax_nopriv_load_more_posts', 'load_more_posts');
add_action('wp_ajax_load_more_posts', 'load_more_posts');
function load_more_posts() {
$next_page = $_POST['current_page'] + 1;
$query = new WP_Query([
'posts_per_page' => 12,
'paged' => $next_page
]);
if ($query->has_posts()):
ob_start();
while($query->have_posts()) : $query->the_post();
get_template_parts('partials/blog','posts');
endwhile;
wp_send_json_success(ob_get_clean());
else:
wp_send_json_error('no more posts');
endif;
}
返回结果依旧是:
data: "no more posts"
success: false
海绵宝宝撒
白板的微信