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

WordPress中ACF get_field返回空及Dokan地区选择不保存问题求助

问题描述
  • 需求:在Dokan多商家后台的新建产品弹窗中,添加ACF创建的「地区」自定义字段下拉选择框
  • 初始问题:使用get_field('regions')获取字段时返回空值,代码位于/wp-content/plugins/dokan-lite/templates/products/tmpl-add-product-popup.php
  • 后续问题:改用get_terms获取region分类术语后,下拉框正常显示,但选择的地区无法保存到数据库

解决方案

1. 解决get_field返回空的问题

get_field()默认依赖当前文章ID,但新建产品弹窗中产品尚未创建,无有效ID,因此直接调用会返回空。需通过ACF字段的唯一ID获取字段选项:

// 替换field_xxxxxx为你的regions字段ID(在ACF字段编辑页面可查看)
$regions_field = acf_get_field('field_xxxxxx');
$regions = $regions_field['choices'];

2. 解决地区无法保存的问题

若region是自定义分类法,需调整表单提交逻辑并添加保存钩子:

修改弹窗中的下拉框代码

<div class="dokan-form-group">
    <?php
        $regions = get_terms([
            'hierarchical' => 1,
            'hide_empty' => 0,
            'taxonomy' => 'region'
        ]);    
    ?>
    <label for="regions"><?php esc_html_e( 'Region', 'your-text-domain' ); ?></label>
    <!-- 重点:name属性改为tax_input[region],适配WordPress分类提交格式 -->
    <select name="tax_input[region]" class="dokan-form-control" id="regions">
        <option value=""><?php esc_html_e( 'Select Region', 'your-text-domain' ); ?></option>
        <optgroup label="Piemonte">
            <?php foreach ( $regions as $region ) { ?>
                <option value="<?php echo esc_attr($region->slug); ?>"> <?php echo esc_html($region->name); ?> </option>
            <?php } ?>
        </optgroup>
    </select>
</div>

添加保存钩子(放入主题functions.php或自定义插件)

如果Dokan默认逻辑未处理自定义分类的保存,需手动添加钩子同步数据:

// 监听产品创建和更新事件
add_action('dokan_new_product_added', 'save_dokan_product_region', 10, 2);
add_action('dokan_product_updated', 'save_dokan_product_region', 10, 2);

function save_dokan_product_region($product_id, $post_data) {
    if (isset($post_data['tax_input']['region']) && !empty($post_data['tax_input']['region'])) {
        wp_set_object_terms($product_id, $post_data['tax_input']['region'], 'region', false);
    } else {
        // 清空已选地区
        wp_set_object_terms($product_id, '', 'region', false);
    }
}

3. 注意事项

  • 确保region分类法已正确注册并关联到product文章类型
  • 避免直接修改Dokan核心模板,建议通过dokan_new_product_popup_before_textarea等钩子注入字段,防止插件更新后代码丢失
  • 若使用ACF关联分类的字段,产品编辑页会自动同步数据,但弹窗需手动处理保存逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 21:30:44