Wordpress 显示最接近今天日期的帖子
我试图显示最接近今天日期的帖子,但到目前为止,运气不佳 假设今天是2014年10月18日,我有两篇帖子,postA的日期是2014年10月17日,postB的日期是2014年10月21日,我希望postA显示出来,因为它离今天最近 我能得到的最接近结果是使用此代码,我知道它离我要寻找的还很远:Wordpress 显示最接近今天日期的帖子,wordpress,Wordpress,我试图显示最接近今天日期的帖子,但到目前为止,运气不佳 假设今天是2014年10月18日,我有两篇帖子,postA的日期是2014年10月17日,postB的日期是2014年10月21日,我希望postA显示出来,因为它离今天最近 我能得到的最接近结果是使用此代码,我知道它离我要寻找的还很远: $today = date('Ymd'); $date = get_sub_field('fixture-date'); // ACF Date Field $args = array( 'post_t
$today = date('Ymd');
$date = get_sub_field('fixture-date'); // ACF Date Field
$args = array(
'post_type' => 'events',
'orderby' => 'meta_value',
'meta_key' => $date,
'order' => 'DESC',
'posts_per_page' => 1,
'meta_query' => array(
'key' => $date,
'value' => $today
'compare' => '>='
),
按日期获取最近的邮件
这里有一个函数,可以在最近的日期前返回帖子。
我给你写了一些评论来解释进展情况
您只能获取post->ID或所有post对象,并根据需要使用它
function get_closet_post_by_date($date) {
global $wpdb;
// Check if there is posts before our $date
$postA = $wpdb->get_row("SELECT ID, post_date FROM {$wpdb->prefix}posts WHERE post_date < '{$date}' ORDER BY post_date DESC LIMIT 1");
// Check if there is posts equals or after our $date
$postB = $wpdb->get_row("SELECT ID, post_date FROM {$wpdb->prefix}posts WHERE post_date >= '{$date}' ORDER BY post_date ASC LIMIT 1");
/*
*
* Convert the posts dates and our $date to time; reduce the post dates from our $date and divide by 60
* The result of this equals to the seconds before of after our $date
*
*/
$postAtime = floor((abs(strtotime($date) - strtotime($postA->post_date)))/(60));
$postBtime = floor((abs(strtotime($date) - strtotime($postB->post_date)))/(60));
// Check which of the posts is closer to our $date
if($postAtime >= $postBtime) {
echo $postB->ID; // Post ID
} else {
echo $postA->ID; // Post ID
}
}
// Run the function
get_closet_post_by_date('2014-08-12');
我做了那样的事,对我来说很有用:
谢谢石壁的回复。我会尽快试一试。希望它能起作用!