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

基于ACF重复字段填充CF7下拉选择框的实现问题

解决ACF重复字段联动Contact Form 7下拉选择框的问题

需求回顾

从自定义文章类型training-course的ACF重复字段course_dates(子字段date-of-choice)中提取日期,在Contact Form 7的下拉选择框date-selector中展示,供用户选择。

原代码核心问题排查

  1. ACF字段名不匹配:原问题中重复字段为course_dates,代码错误写成course-dates(下划线误写为横杠),ACF字段名严格区分下划线/横杠命名。
  2. CF7标签类型错误:需求是下拉选择框,原短码使用[radio]单选框,不符合需求。
  3. 未处理重复日期:多课程重复日期会重复显示,影响体验。
  4. 查询参数不完善:get_posts未显式指定post_status,可能遗漏已发布内容;缺少查询优化参数。
  5. 日期格式不友好:ACF日期字段默认存储YYYYMMDD格式,前端展示需转换为易读格式。

修正后的代码

function dynamic_course_date_selector($scanned_tag, $replace) {
    // 仅处理指定名称的CF7字段
    if ($scanned_tag['name'] !== 'date-selector') {
        return $scanned_tag;
    }

    // 获取所有已发布的training-course文章,优化查询性能
    $courses = get_posts([
        'post_type'      => 'training-course',
        'numberposts'    => -1,
        'orderby'        => 'title',
        'order'          => 'ASC',
        'post_status'    => 'publish',
        'no_found_rows'  => true,
    ]);

    if (empty($courses)) {
        return $scanned_tag;
    }

    $all_dates = [];

    foreach ($courses as $course) {
        // 获取ACF重复字段,确保字段名与后台设置一致
        $course_dates = get_field('course_dates', $course->ID);
        
        if (empty($course_dates)) {
            continue;
        }

        foreach ($course_dates as $date_item) {
            $raw_date = $date_item['date-of-choice'];
            if (empty($raw_date)) {
                continue;
            }

            // 转换为易读的YYYY-MM-DD格式,可根据需求调整
            $formatted_date = date('Y-m-d', strtotime($raw_date));
            // 去重处理
            if (!in_array($formatted_date, $all_dates)) {
                $all_dates[] = $formatted_date;
            }
        }
    }

    // 更新CF7字段选项
    if (!empty($all_dates)) {
        // 按日期升序排序
        sort($all_dates);
        // 生成CF7要求的value|label格式
        $raw_values = array_map(function($date) {
            return "{$date}|{$date}";
        }, $all_dates);

        $pipes = new WPCF7_Pipes($raw_values);
        $scanned_tag['values'] = $pipes->collect_befores();
        $scanned_tag['pipes'] = $pipes;
    }

    return $scanned_tag;
}
add_filter('wpcf7_form_tag', 'dynamic_course_date_selector', 10, 2);

正确的CF7短码

[select date-selector include_blank default:1]
  • include_blank:添加空占位选项,引导用户选择(不需要可删除)
  • default:1:默认选中第一个非空选项(若要默认空选项,改为default:0)

额外注意事项

  • 确认ACF字段名完全匹配:重复字段名course_dates、子字段名date-of-choice需与后台ACF设置完全一致,大小写敏感。
  • 日期格式自定义:如需中文格式(如2024年5月20日),将date('Y-m-d', strtotime($raw_date))改为date('Y年m月d日', strtotime($raw_date))。
  • 缓存问题:更新课程日期后前端无变化时,需清除网站缓存或Contact Form 7的缓存。
  • 权限调整:若需展示私有课程的日期,可将post_status改为['publish', 'private']。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 22:55:24