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

如何实现日期过期后删除ACF Repeater的对应行

处理ACF Repeater字段中的过期日期行

实现思路

  1. 生成与存储格式一致的当前日期(Y-m-d)
  2. 遍历目标文章,获取Repeater字段的所有行
  3. 筛选出日期不早于当前日期的行,丢弃过期行
  4. 将筛选后的有效行重新保存回Repeater字段

核心代码实现

function delete_expired_acf_repeater_rows() {
    // 生成当前日期,格式匹配存储的Y-m-d
    $current_date = date('Y-m-d');
    
    // 替换为你需要处理的文章类型,如'post'、'page'或自定义类型
    $target_post_type = 'your_post_type';
    
    // 获取所有目标类型的已发布文章(仅取ID提升性能)
    $posts = get_posts([
        'post_type'      => $target_post_type,
        'posts_per_page' => -1,
        'post_status'    => 'publish',
        'fields'         => 'ids'
    ]);
    
    foreach ($posts as $post_id) {
        // 获取Repeater字段数据
        $repeater_rows = get_field('pasirinkti_datas', $post_id);
        $valid_rows = [];
        
        if (!empty($repeater_rows)) {
            foreach ($repeater_rows as $row) {
                $trip_date = $row['keliones_datos'];
                
                // Y-m-d格式的日期字符串可直接按字符顺序比较
                if ($trip_date >= $current_date) {
                    $valid_rows[] = $row;
                }
            }
            
            // 更新字段,仅保留有效行
            update_field('pasirinkti_datas', $valid_rows, $post_id);
        }
    }
}

触发方式选择

方式1:测试用后台触发

取消注释后,每次后台页面加载时执行清理(仅建议测试阶段使用):

// add_action('admin_init', 'delete_expired_acf_repeater_rows');

方式2:定时自动清理(推荐)

设置每天凌晨自动执行,无需手动操作:

// 注册定时任务
function schedule_expired_rows_cleanup() {
    if (!wp_next_scheduled('cleanup_expired_acf_rows')) {
        wp_schedule_event(strtotime('today 00:00'), 'daily', 'cleanup_expired_acf_rows');
    }
}
add_action('wp', 'schedule_expired_rows_cleanup');

// 绑定清理函数到定时钩子
add_action('cleanup_expired_acf_rows', 'delete_expired_acf_repeater_rows');

注意事项

  • 运行前务必备份数据库,防止数据丢失
  • 若处理大量文章,建议添加分批逻辑避免性能损耗
  • 确保字段名称pasirinkti_datas和keliones_datos与ACF后台配置完全一致
  • 如需处理特定文章,可在get_posts中添加post__in参数指定目标ID列表

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 19:45:40