我希望能够计算帖子创建的天数并与今天进行比较以回显“今天/昨天/上周/上个月”。 我从 get_the_date() 获得的日期格式是“2015 年 12 月 1 日”,所以我想知道是否需要使用我不知道的不同函数。
您只需要 get_the_date() 函数;
现在日期应采用 YYYY-MM-DD 格式
为此
$date1 = date('Y-m-d', strtotime(get_the_date())) ;
$current_date1 = date('Y-m-d', time()) ;
现在使用这个功能
function dateDifference($date_1 , $date_2 )
{
$datetime1 = date_create($date_1);
$datetime2 = date_create($date_2);
$interval = date_diff($datetime1, $datetime2);
return $interval->format('%a');
}
//call above function
echo $days = dateDifference($date1, $current_date1);
我不确定是否有任何 WordPress 函数,但您可以使用内置 PHP 函数获取您的值。
昨天:
date('Y-m-d', strtotime("-1 day"));
上周
date('Y-m-d', strtotime("-1 week +1 day"));
上个月
date('Y-m-'.1, strtotime("-1 month")); //First day of -1 month
您可以在这里阅读有关 strtotime 的更多信息 http://php.net/manual/en/function.strtotime.php
如果您之前没有使用过日期函数,这里还有一个日期函数的链接:http://php.net/manual/en/function.date.php
您可能希望使用 Y-m-d 格式进行 WordPress 查询,请在此处阅读更多相关信息:http://php.net/manual/en/function.date.php
如果你像我一样从谷歌来到这里,我相信这就是 2024 年实现这一目标的方法:
function mp_days_since_post($date) {
date_default_timezone_set('Europe/Berlin');
$now = new DateTimeImmutable();
$interval = $date->diff($now);
return $interval->format('%a');
}
这将返回自特定日期以来的天数(请参阅docs了解返回格式),您可以像这样使用:
if (intval(days_since_post(get_the_date())) <= 7) {
echo "Last Week"
}
或者调整您的辅助函数以立即返回正确的字符串。