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

如何在ACF Pro Repeater字段中存储行添加/更新的日期时间?

在ACF Repeater字段中自动追踪每行更新的日期时间

当然可以实现,不需要额外创建自定义文章类型,下面是两种相对简单的方案:

方案1:手动添加日期时间字段(最简入门版)

  • 编辑你的Project Updates Repeater字段,在里面新增一个日期时间选择器字段(建议命名为update_datetime)
  • 可以将该字段设置为「只读」或「隐藏」,如果不需要手动调整时间,后续配合自动填充逻辑即可
  • 前端展示时,直接调用这个字段的值即可

方案2:自动填充日期时间(推荐,无需手动操作)

通过ACF的钩子函数,在添加或修改Repeater行时自动写入当前时间。具体步骤:

  1. 先按方案1的步骤,在Repeater里新增一个日期时间字段(记下字段键,比如update_datetime对应的字段键是field_123456)
  2. 将以下代码添加到主题的functions.php文件或自定义插件中:
add_action('acf/update_value', 'auto_set_repeater_update_time', 10, 3);
function auto_set_repeater_update_time($value, $post_id, $field) {
    // 替换为你的Project Updates Repeater字段的键
    $target_repeater_key = 'field_abcdef';
    // 替换为你新增的日期时间字段的键
    $target_datetime_key = 'field_123456';

    if ($field['key'] !== $target_repeater_key) {
        return $value;
    }

    if (is_array($value)) {
        foreach ($value as &$row) {
            // 每次保存时自动更新当前行的时间(如果需要仅新增时设置,注释当前行,启用下面的判断代码)
            $row[$target_datetime_key] = current_time('mysql');
            // if (empty($row[$target_datetime_key])) {
            //     $row[$target_datetime_key] = current_time('mysql');
            // }
        }
    }

    return $value;
}
  1. 替换代码中的两个字段键:从ACF字段编辑页面可以复制到对应的字段键(字段编辑页URL里的key参数,或页面底部的「字段键」区域)

前端展示示例

在项目文章模板中,循环输出Repeater内容时带上时间:

if (have_rows('project_updates')) {
    while (have_rows('project_updates')) {
        the_row();
        $content = get_sub_field('update_content');
        $raw_time = get_sub_field('update_datetime');
        $formatted_time = date('Y年m月d日 H:i', strtotime($raw_time));

        echo <<<HTML
<div class="project-update">
    <div class="update-time">{$formatted_time}</div>
    <div class="update-content">{$content}</div>
</div>
HTML;
    }
}

这个方案完全满足你的需求:所有更新内容保留在项目文章内,无需切换文章类型,也不会出现关联错误的问题。

内容的提问来源于stack exchange,提问作者theflatbranch

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 21:28:19