EDIT : I answered myself.
简单的请求。我正在尝试开发一个代码,用于搜索今天的帖子。如果没有返回任何内容,请在今天之前获取最新帖子。
现在,我已经做了一个小算法来揭示你的我的问题。
<?php
// WP_Query arguments
$args = array (
\'post_type\' => array( \'post\' ),
\'year\' => date(\'Y\'),
\'monthnum\' => date(\'m\'),
\'day\' => date(\'d\'),
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// do something
}
} else {
// no posts found (Here I need to make the new request)
$args_before = array (
\'post_type\' => array( \'post\' ),
\'year\' => date(\'Y\'),
\'monthnum\' => date(\'m\'),
\'day\' => date(\'d\'),
);
// Classic query will go here ...
}
// Restore original Post Data
wp_reset_postdata();
?>
我从搜索今天帖子的第一个数组($args)开始,然后检查是否有结果。
棘手的是,如果我没有帖子,我需要在else{}工作吗?我怎样才能在今天之前获得之前的第一篇帖子?
我需要与BETWEEN
和ORDER DESC
?
有什么线索吗?
最合适的回答,由SO网友:Maikal 整理而成
我认为您应该创建一个递归函数,如果没有找到传递新日期的帖子,该函数将调用自身。。
function getDatePosts( $date, $query_args ) {
$query_args[\'date_query\'] = array(
\'year\' => date( \'Y\', $date ),
\'mounth\' => date( \'m\', $date ),
\'day\' => date( \'d\', $date )
);
$query = new WP_Query( $query_args );
if( ! $query->have_posts() ) {
$date = $date - ( 60 * 60 * 24 );
$query = getDatePosts( $date, $query_args );
}
return $query;
}
并在模板中使用它:
$query = getDatePosts( time(), array( \'post_type\' => \'post\', \'posts_per_page\' => 5 ) );
while( $query->have_posts() ) : $query->the_post();
// output
endwhile;
未经测试,但应能正常工作。
SO网友:Patrice Poliquin
我在这一页上找到了一些帮助我完成请求的东西。
How to get posts published between a date and today?
Use date_query
\'date_query\' => array(
\'column\' => \'post_date\',
\'after\' => \'- 30 days\'
),
正如您所看到的,我们可以检查列post\\u date,并要求他们返回。
// WP_Query arguments
$args = array (
\'post_type\' => array( \'post\' ),
\'year\' => date(\'Y\'),
\'monthnum\' => date(\'m\'),
\'day\' => date(\'d\'),
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// do something
}
} else {
// no posts found
$args_previous = array (
\'post_status\' => \'publish\',
\'date_query\' => array(
\'column\' => \'post_date\',
\'after\' => \'- 30 days\'
),
\'order\' => \'DESC\',
\'orderby\' => \'date\',
\'posts_per_page\' => \'1\'
);
// The Query
$query_previous = new WP_Query( $args_previous );
if ( $query_previous->have_posts() ) {
while ( $query_previous->have_posts() ) {
$query_previous->the_post();
// do something
}
} else {
echo \'Really, you have no post!\';
}
}
// Restore original Post Data
wp_reset_postdata();