如何修改WordPress的日期时间格式为相对时间显示
WordPress 实现文章相对时间显示的方法
方法一:直接使用内置函数 human_time_diff()
WordPress 自带了 human_time_diff() 函数,可计算两个时间戳的差值并返回友好的相对时间文本。找到主题模板中显示文章日期的代码(通常在 index.php、single.php、archive.php 等文件里),替换原有日期输出代码即可。
- 原有日期代码示例(可能是以下其中一种):
<?php the_date(); ?> <!-- 或者 --> <?php the_time('F j, Y'); ?>
- 替换为相对时间代码:
<?php echo human_time_diff(get_the_time('U'), current_time('timestamp')) . '前'; ?>
方法二:自定义可复用函数
如果需要在多个地方调用相对时间,可在主题的 functions.php 文件中添加自定义函数,之后在模板里直接调用:
- 在
functions.php末尾添加以下代码:
function custom_relative_post_date() { // 获取文章发布时间戳 $post_timestamp = get_the_time('U'); // 获取当前时间戳 $current_timestamp = current_time('timestamp'); // 计算相对时间 $relative_time = human_time_diff($post_timestamp, $current_timestamp); // 返回带“前”的文本 return $relative_time . '前'; }
- 在模板需要显示日期的地方调用该函数:
<?php echo custom_relative_post_date(); ?>
进阶:保留具体日期提示
如果想让用户鼠标悬停时看到具体发布日期,可结合 HTML time 标签的 title 属性:
<time datetime="<?php echo get_the_date('c'); ?>" title="<?php echo get_the_date(); ?>"> <?php echo human_time_diff(get_the_time('U'), current_time('timestamp')) . '前'; ?> </time>
注意事项
- 修改主题文件前建议先备份,或使用子主题,避免主题更新时代码丢失。
- 如果使用区块编辑器(Gutenberg),可添加“自定义 HTML”区块插入上述 PHP 代码(确保主题支持在区块中执行 PHP,或使用代码片段插件辅助)。
内容的提问来源于stack exchange,提问作者vania web
相关产品推荐
相关产品推荐

