<?php
/* AJAX.php */
//ajax call with no privalidges, a user that is not logged can access load-more
add_action(\'wp_ajax_nopriv_japi_load_more\',\'japi_load_more\');
add_action(\'wp_ajax_japi_load_more\',\'japi_load_more\');
function japi_load_more(){
$year = htmlspecialchars(trim($_POST[\'digwp_y\']));
$month = htmlspecialchars(trim($_POST[\'digwp_m\']));
$day = htmlspecialchars(trim($_POST[\'digwp_d\']));
query_posts(array(\'year\'=>$year,\'monthnum\'=>$month,\'day\'=>$day,\'posts_per_page\'=>-1 ));
if (have_posts()) : while (have_posts()) : the_post();
?>
<?php get_template_part(\'content\',get_post_format()); ?>
<?php
endwhile; else:
echo "<p style=\'text-align: center; font-size: 15px; padding: 5px;\'>Nothing found.</p>";
endif;
wp_reset_postdata();
die();
}
如何显示特定日期的帖子?
1 个回复
最合适的回答,由SO网友:Johansson 整理而成
第一件事第一。不是吗query_posts()
. 使用WP_Query
相反,为了防止弄乱主查询。
现在,关于你的问题。WP_Query
也允许您输入数据参数。它甚至有一个日期查询,你可以在我提供的链接中查看它。
不必使用管理AJAX,您可以为自己编写一个简单的REST-API端点,该端点更快、更简单,并且可以执行相同的操作(甚至更多!)。但由于我不知道你模板的内容,我将跳过这个。
那么,让我们将您的代码转换为:
add_action(\'wp_ajax_nopriv_japi_load_more\',\'japi_load_more\');
add_action(\'wp_ajax_japi_load_more\',\'japi_load_more\');
function japi_load_more(){
// Get the parameters
$year = htmlspecialchars(trim($_POST[\'digwp_y\']));
$month = htmlspecialchars(trim($_POST[\'digwp_m\']));
$day = htmlspecialchars(trim($_POST[\'digwp_d\']));
// Set the date in the Query
$args = array(
\'posts_per_page\' => -1
\'year\' => $year,
\'monthnum\' => $month, // Number of the month, not name
\'day\' => $day,
);
$query = new WP_Query($args);
//Run the loop
if( $query->have_posts() ) {
while( $query->have_posts() ){
$query->the_post();
get_template_part(\'content\',get_post_format());
}
} else {
echo "<p style=\'text-align: center; font-size: 15px; padding: 5px;\'>".__(\'Nothing found.\',\'text-domain\')."</p>";
}
}
结束