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

如何在WooCommerce产品数据自定义标签页中添加ACF字段组

实现ACF字段组显示在自定义WooCommerce产品标签页

步骤1:添加ACF自定义位置规则选项

要让你的自定义标签页出现在ACF的位置选择下拉菜单中,需要通过ACF的过滤器注册新的位置规则:

// 注册ACF位置规则类型
add_filter('acf/location/rule_types', 'cg_narrowfar_add_acf_location_rule');
function cg_narrowfar_add_acf_location_rule($choices) {
    // 添加"WooCommerce产品标签页"规则组
    $choices['WooCommerce']['product_tab'] = __('WooCommerce 产品标签页', 'narrowfar-integration-for-woocommerce');
    return $choices;
}

// 注册规则对应的可选值(关联你的自定义标签页ID)
add_filter('acf/location/rule_values/product_tab', 'cg_narrowfar_add_acf_location_values');
function cg_narrowfar_add_acf_location_values($choices) {
    $choices['narrowfar_product_data'] = __('Narrowfar Data', 'narrowfar-integration-for-woocommerce');
    return $choices;
}

步骤2:实现位置规则的匹配逻辑

接下来需要告诉ACF何时触发该规则,判断当前是否处于你的自定义产品标签页:

add_filter('acf/location/rule_match/product_tab', 'cg_narrowfar_match_acf_location', 10, 3);
function cg_narrowfar_match_acf_location($match, $rule, $options) {
    // 检查当前是否在产品编辑页面
    if (isset($_GET['post_type']) && $_GET['post_type'] === 'product') {
        global $current_screen;
        if ($current_screen->id === 'product') {
            // 获取当前激活的标签页
            $selected_tab = isset($_GET['tab']) ? $_GET['tab'] : 'general';
            // 根据规则运算符判断匹配结果
            if ($rule['operator'] === '==') {
                $match = ($selected_tab === $rule['value']);
            } elseif ($rule['operator'] === '!=') {
                $match = ($selected_tab !== $rule['value']);
            }
        }
    }
    return $match;
}

步骤3:在自定义标签页中渲染ACF字段

最后,在自定义标签页的内容钩子中渲染ACF字段组:

// 渲染自定义标签页的内容
add_action('woocommerce_product_data_panels', 'cg_narrowfar_render_product_tab_content');
function cg_narrowfar_render_product_tab_content() {
    global $post;
    ?>
    <div id="narrowfar_product_fields" class="panel woocommerce_options_panel">
        <?php
        // 方式1:直接指定字段组ID/key渲染
        acf_render_field_group('group_your_field_group_key');
        
        // 方式2:自动匹配位置规则对应的字段组
        // $field_groups = acf_get_field_groups(array('product_tab' => 'narrowfar_product_data'));
        // foreach($field_groups as $group) {
        //     acf_render_field_group($group);
        // }
        ?>
    </div>
    <?php
}

配置ACF字段组

进入ACF后台创建字段组,在位置规则中选择:

  • 规则组:WooCommerce 产品标签页
  • 规则值:Narrowfar Data
    保存后,ACF字段(包括图片上传字段)就会自动显示在你的自定义产品标签页中,无需手动处理复杂字段的前端逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 02:27:48