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

如何在WordPress中实现访客点击文章时更新已发布文章Post Meta显示当前时间

解决WordPress单文章访问时更新Post Meta记录当前时间

原代码问题分析

你的代码存在两个核心问题:

  • 遍历所有文章修改post_date,这会批量修改所有文章的发布日期,完全偏离了"仅更新当前被访问文章"的需求
  • 错误修改了文章本身的发布日期字段,而需求是更新**Post Meta(自定义字段)**来存储访问时间,不应改动文章的原始发布信息

正确实现代码

在主题的functions.php文件中添加以下代码,实现访客访问单文章时自动更新该文章的自定义字段记录当前时间:

// 单文章访问时更新自定义字段记录当前时间
add_action('template_redirect', 'update_post_last_visited_meta');
function update_post_last_visited_meta() {
    // 仅在已发布的单文章页面执行
    if (is_single() && get_post_status(get_the_ID()) === 'publish') {
        $post_id = get_the_ID();
        $current_time = current_time('mysql'); // 采用WordPress标准时间格式
        
        // 更新或创建自定义字段last_visited_time
        update_post_meta($post_id, 'last_visited_time', $current_time);
    }
}

在文章页面显示访问时间

如果需要在单文章页面显示这个访问时间,在主题的single.php(或你使用的单文章模板文件)中合适位置添加以下代码:

// 获取并格式化显示最后访问时间
$last_visited = get_post_meta(get_the_ID(), 'last_visited_time', true);
if ($last_visited) {
    $formatted_time = date('Y年m月d日 H:i:s', strtotime($last_visited));
    echo '<p>最后访问时间:' . $formatted_time . '</p>';
}

代码说明

  • 使用template_redirect钩子:在WordPress确定模板后、输出内容前触发,确保只在有效页面执行
  • is_single()判断当前是单文章页面,get_post_status()确保文章是已发布状态
  • update_post_meta()负责更新自定义字段,第三个参数true表示该字段为单值(而非数组),不存在则自动创建
  • 时间格式采用current_time('mysql'),和WordPress内部存储格式一致,便于后续格式化处理

内容的提问来源于stack exchange,提问作者247NAIJABUZZ ENTERTAINMENT

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 09:50:14