我试图显示距今天最近的帖子,但到目前为止,没有运气。
让我们说今天是2014年10月18日,我有2个帖子, postA 的日期为17/10/2014, postB 的日期为21/10 / 2014,我希望 postA 显示因为今天最近。
我能得到的最接近的结果是这个代码,我知道它仍然远远不是我想要的东西:)
$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' => '>='
),
答案 0 :(得分:1)
这是一个可以在最近的日期返回帖子的功能 我给你写了一些评论来解释你的进展。
您只能获得post-gt; ID或所有帖子对象,并根据需要使用它。
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');
答案 1 :(得分:0)
我做的那样,它对我有用:
<?php
$year = strftime('%Y');
$month = strftime('%m');
$day = strftime('%e');
$argsi = array(
'numberposts' => 1,
'post_type' => $posttype,
'orderby' => 'date',
'order' => 'ASC',
'date_query' => array(
'after' => array(
'year' => $year,
'month' => $month,
'day' => $day
),
'inclusive' => 'true'
)
);
$recent_post = new WP_Query($argsi);
foreach ($recent_post as $recent)
{
echo get_the_title($recent["ID"]);
echo get_the_content($recent["ID"]);
}
?>
&#13;
使用&#39; get _&#39;这些功能非常重要。 $ posttype可以很简单&#39; post&#39;或您的自定义帖子类型。