如何将WooCommerce品牌名称同步为商品属性?
WooCommerce品牌同步到商品属性的解决方案
一、先确认品牌插件的分类法名称
你不确定的product_brand是否正确,可以用以下方法快速验证:
- 临时在主题的
functions.php里加一段代码,打印所有商品相关的分类法:
add_action('admin_init', function() { $taxonomies = get_taxonomies(['object_type' => ['product']], 'names'); echo '<pre>'; print_r($taxonomies); echo '</pre>'; });
刷新后台后,就能看到所有和商品关联的分类法名称,找和品牌相关的(比如product_brand、pa_brand或者brand),找到后删掉这段代码即可。
二、创建WooCommerce品牌属性
你找不到“brand”属性,是因为需要手动在后台创建:
- 进入WooCommerce后台 → 产品 → 属性 → 点击「添加新属性」
- 属性名称填「品牌」
- 属性slug填
brand(小写无空格) - 勾选「启用存档」(可选),然后点击「添加属性」
- 创建后,系统会自动生成前缀为
pa_的元键(即pa_brand),这是WooCommerce商品属性的标准存储格式。
三、修正同步代码
你原来的代码直接用update_post_meta存brand是错误的,因为WooCommerce的属性需要关联术语ID,且元键是pa_brand。以下是修正后的代码:
function transfer_brand_to_attribute( $post_id ) { // 跳过自动保存和修订版 if ( wp_is_post_autosave( $post_id ) || wp_is_post_revision( $post_id ) ) { return; } // 确认当前是产品类型 if ( get_post_type( $post_id ) !== 'product' ) { return; } // 替换这里的分类法名称为你刚才查到的(比如product_brand) $brand_taxonomy = 'product_brand'; $brands = wp_get_post_terms( $post_id, $brand_taxonomy, ['fields' => 'ids'] ); if ( ! empty( $brands ) ) { // WooCommerce品牌属性的元键(pa_ + 属性slug) $attribute_key = 'pa_brand'; // 设置商品属性值(存储术语ID) update_post_meta( $post_id, '_' . $attribute_key, $brands[0] ); update_post_meta( $post_id, $attribute_key, $brands[0] ); // 同步到产品的属性数组(确保前端显示) $product_attributes = get_post_meta( $post_id, '_product_attributes', true ) ?: []; $product_attributes[$attribute_key] = [ 'name' => $attribute_key, 'value' => $brands[0], 'is_visible' => '1', 'is_variation' => '0', 'is_taxonomy' => '1' ]; update_post_meta( $post_id, '_product_attributes', $product_attributes ); } } add_action( 'save_post_product', 'transfer_brand_to_attribute', 10, 1 );
- 注意把
$brand_taxonomy的值替换成你查到的品牌分类法名称 - 用
save_post_product钩子替代save_post,只针对产品类型触发,更精准
四、验证效果
- 新增或编辑一个产品,选择品牌后保存
- 查看产品编辑页面的「产品数据」→「属性」标签,就能看到自动添加的「品牌」属性和对应的名称
- 前端产品页面也会显示该品牌属性
内容的提问来源于stack exchange,提问作者Jon Dolsson
相关产品推荐
相关产品推荐

