You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WordPress中显示文章最后更新日期?代码实现指引

Got it! 我帮你把这段代码补全并整理成可直接使用的版本,同时附上详细操作步骤和优化建议:

在WordPress文章中显示最后更新日期的实现方案

完整代码实现

首先把你提供的代码补全并优化,确保逻辑完整且兼容常规场景:

function wpb_last_updated_date( $content ) {
    $u_time = get_the_time('U');
    $u_modified_time = get_the_modified_time('U');
    
    // 仅在文章详情页显示,且修改时间比发布时间晚至少1天(避免刚发布就显示更新)
    if (is_single() && $u_modified_time >= $u_time + 86400) {
        $updated_date = get_the_modified_time('F jS, Y');
        $updated_time = get_the_modified_time('h:i a');
        $custom_content = '<p class="last-updated">Last updated on '. $updated_date . ' at '. $updated_time .'</p>';
        
        // 把更新日期插入到文章内容开头(想放结尾就改成 $content . $custom_content)
        $content = $custom_content . $content;
    }
    
    return $content;
}
add_filter( 'the_content', 'wpb_last_updated_date' );

操作步骤

  1. 登录WordPress后台,进入「外观」→「主题文件编辑器」
  2. 在右侧主题文件列表中找到并点击functions.php(部分主题显示为「主题函数」)
  3. 将上述完整代码粘贴到文件末尾的空行处(不要覆盖原有代码,避免破坏主题功能)
  4. 点击「更新文件」保存修改即可

自定义优化建议

  • 调整日期时间格式:可以修改get_the_modified_time()里的参数,比如:
    • 改成'Y-m-d'显示2024-05-20格式的日期
    • 改成'H:i'显示14:30这样的24小时制时间
  • 调整显示位置:如果想把更新日期放在文章内容结尾,把代码里的$content = $custom_content . $content;改成$content = $content . $custom_content;
  • 美化样式:可以在主题的「自定义」→「额外CSS」中添加以下代码,让更新日期更显眼:
.last-updated {
    color: #666;
    font-style: italic;
    padding: 8px 0;
    border-top: 1px solid #eee;
    margin-bottom: 15px;
}

内容的提问来源于stack exchange,提问作者m-mas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:09:07