如何在WordPress中计算发布日期到当前日期的间隔天数
实现WordPress文章显示发布至今的间隔天数
你可以通过时间戳计算的方式替换原有的get_the_date()调用,直接输出文章发布至今的间隔天数,具体代码如下:
// 获取文章发布时间的UTC Unix时间戳 $post_timestamp = get_post_time('U', true); // 获取当前UTC时间戳 $current_timestamp = current_time('timestamp', true); // 计算时间差并转换为天数 $days_published = floor(($current_timestamp - $post_timestamp) / (60 * 60 * 24)); // 输出结果 echo "该文章已发布 {$days_published} 天";
细节说明:
get_post_time('U', true):第二个参数true指定使用UTC时区,避免站点时区设置导致的计算偏差;U表示返回Unix时间戳格式。- 如果希望当天发布的文章显示为1天,可以把
floor()替换为ceil(),或者调整计算式为ceil(($current_timestamp - $post_timestamp + 1) / (60 * 60 * 24))。 - 将这段代码放到主题模板中原本调用
get_the_date()的位置即可,比如single.php、content.php等文件的日期显示区域。
内容的提问来源于stack exchange,提问作者Abhiupadhyay
相关产品推荐
相关产品推荐

