You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

WooCommerce:编辑产品时为下拉属性新增自定义输入功能需求

嘿,我刚好处理过类似的需求,给你拆解下具体的实现步骤和代码,应该能完美解决你的问题!

核心思路

WooCommerce产品编辑页的属性 metabox 是通过专属钩子渲染的,我们需要做两件事:一是在目标属性的下拉框后新增文本输入框,二是在产品保存时处理新输入的值——把它添加到属性的可选值列表,同时绑定到当前产品上。

具体实现步骤

1. 给目标属性添加文本输入框

我们用woocommerce_product_after_attribute_settings钩子,它会在每个属性设置行的末尾触发。我们只需要针对名为arguments的选择型属性,输出自定义文本框即可:

add_action('woocommerce_product_after_attribute_settings', 'add_argument_custom_input', 10, 3);
function add_argument_custom_input($loop, $attribute, $variations) {
    // 只针对slug为pa_arguments的选择型属性(WooCommerce属性slug默认带pa_前缀)
    if ($attribute['name'] === 'pa_arguments' && $attribute['type'] === 'select') {
        ?>
        <div class="form-field" style="display: inline-block; margin-left: 15px;">
            <label><?php esc_html_e('添加新值', 'your-text-domain'); ?></label>
            <input type="text" id="custom_arg_val_<?php echo $loop; ?>" 
                   name="custom_arg_val[<?php echo $loop; ?>]" 
                   placeholder="<?php esc_attr_e('输入新的属性值', 'your-text-domain'); ?>"
                   style="width: 200px;" />
        </div>
        <?php
    }
}

2. 处理表单提交,保存新属性值

woocommerce_process_product_meta钩子,在产品保存时捕获文本框的输入值,判断是否为新值,然后添加到属性术语库并绑定到当前产品:

add_action('woocommerce_process_product_meta', 'save_custom_argument_value', 10, 1);
function save_custom_argument_value($product_id) {
    if (!isset($_POST['custom_arg_val']) || !is_array($_POST['custom_arg_val'])) {
        return;
    }

    $product = wc_get_product($product_id);
    $attributes = $product->get_attributes();

    foreach ($_POST['custom_arg_val'] as $loop => $new_value) {
        $new_value = sanitize_text_field($new_value);
        if (empty($new_value)) continue;

        // 定位到arguments属性
        foreach ($attributes as $attr_key => $attribute) {
            if ($attr_key !== 'pa_arguments') continue;

            // 获取当前属性已有的所有可选值
            $existing_terms = get_terms(array(
                'taxonomy' => $attr_key,
                'hide_empty' => false,
            ));
            $existing_values = wp_list_pluck($existing_terms, 'name');

            // 如果新值不存在,添加为新的属性术语
            if (!in_array($new_value, $existing_values)) {
                wp_insert_term($new_value, $attr_key);
            }

            // 将新值设置为当前产品的该属性值
            $attribute->set_options(array($new_value));
            $product->set_attributes($attributes);
            $product->save();
            break;
        }
    }
}

3. 额外注意点

  • 确认你的属性slug是pa_arguments:WooCommerce创建属性时,会自动给slug加上pa_前缀,如果你的属性slug不同,记得替换代码里的对应值。
  • 样式可以根据自己的需求调整,上面的代码已经加了基础的行内样式让文本框和下拉框对齐,你也可以用admin_head钩子加载自定义CSS优化显示。

这样操作后,你在产品编辑页的arguments属性下拉框后面就会看到一个文本输入框,输入新值保存后,这个值会自动加入属性的可选值列表,同时当前产品也会使用这个新值。

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

火山引擎 最新活动