php 如何在自定义 WP_Query Ajax 上实现分页
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29595391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to implement pagination on a custom WP_Query Ajax
提问by Jane Smith
I want to paginate my WordPress posts in a custom loop with Ajax, so when I click on load more button posts will appear.
我想使用 Ajax 在自定义循环中对我的 WordPress 帖子进行分页,因此当我单击加载更多按钮时,会出现帖子。
My code:
我的代码:
<?php
$postsPerPage = 3;
$args = array(
'post_type' => 'post',
'posts_per_page' => $postsPerPage,
'cat' => 1
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
?>
<h1><?php the_title(); ?></h1>
<p>
<?php the_content(); ?>
</p>
<?php
endwhile;
echo '<a href="#">Load More</a>';
wp_reset_postdata();
?>
This code does not paginate. Is there a better way to do this?
此代码不分页。有一个更好的方法吗?
回答by Kivylius
The Load More
button needs to send a ajax
request to the server and the returned data can be added to the existent content using jQuery or plain javascript. Assuming your using jQuery this would starter code.
该Load More
按钮需要向ajax
服务器发送请求,返回的数据可以使用 jQuery 或普通 javascript 添加到现有内容中。假设您使用 jQuery,这将是入门代码。
Custom Ajax Handler (Client-side)
自定义 Ajax 处理程序(客户端)
<a href="#">Load More</a>
Change to:
改成:
<a id="more_posts" href="#">Load More</a>
Javascript:- Put this at the bottom of the file.
Javascript:- 把它放在文件的底部。
//</script type="text/javascript">
var ajaxUrl = "<?php echo admin_url('admin-ajax.php')?>";
var page = 1; // What page we are on.
var ppp = 3; // Post per page
$("#more_posts").on("click",function(){ // When btn is pressed.
$("#more_posts").attr("disabled",true); // Disable the button, temp.
$.post(ajaxUrl, {
action:"more_post_ajax",
offset: (page * ppp) + 1,
ppp: ppp
}).success(function(posts){
page++;
$(".name_of_posts_class").append(posts); // CHANGE THIS!
$("#more_posts").attr("disabled",false);
});
});
//</script>
Custom Ajax Handler (Server-side)PHP- Put this in the functions.php file.
自定义 Ajax 处理程序(服务器端)PHP- 将其放在 functions.php 文件中。
function more_post_ajax(){
$offset = $_POST["offset"];
$ppp = $_POST["ppp"];
header("Content-Type: text/html");
$args = array(
'post_type' => 'post',
'posts_per_page' => $ppp,
'cat' => 1,
'offset' => $offset,
);
$loop = new WP_Query($args);
while ($loop->have_posts()) { $loop->the_post();
the_content();
}
exit;
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');