WooCommerce程序化设置产品Brands属性:检查并添加品牌
WooCommerce 产品绑定Apple品牌实现方案
需求说明
检查WooCommerce全局产品属性「Brands」中是否存在“Apple”术语:
- 若存在,直接将该品牌以分类法类型绑定到指定产品
- 若不存在,先添加“Apple”品牌术语,再关联至指定产品
完整实现代码
$product_id = 214246; $product = wc_get_product($product_id); // 检查产品是否存在 if ($product) { // 全局品牌属性对应的分类法slug(根据实际属性slug调整,默认属性slug为brand时是pa_brand) $brand_taxonomy = 'pa_brand'; // 检查"Apple"术语是否存在 $apple_term = term_exists('Apple', $brand_taxonomy); // 如果术语不存在,创建它 if (!$apple_term) { $apple_term = wp_insert_term( 'Apple', // 术语名称 $brand_taxonomy, // 分类法 array( 'slug' => 'apple' // 术语slug,可自定义 ) ); } // 确保创建/获取术语成功 if (!is_wp_error($apple_term)) { $term_id = is_array($apple_term) ? $apple_term['term_id'] : $apple_term; // 将术语关联到产品 wp_set_object_terms( $product_id, $term_id, $brand_taxonomy, true // true为追加品牌,false为替换现有品牌 ); // 可选:刷新产品缓存 $product->save(); echo '产品已成功绑定Apple品牌'; } else { echo '创建/获取Apple品牌失败:' . $apple_term->get_error_message(); } // 保留原有的属性显示逻辑(可选) $attributes = $product->get_attributes(); if (!empty($attributes)) { foreach ($attributes as $attribute) { $attribute_label = wc_attribute_label($attribute->get_name()); $attribute_value = ''; if ($attribute->is_taxonomy()) { $attribute_value = implode(', ', wc_get_product_terms($product->get_id(), $attribute->get_name(), array('fields' => 'names'))); } echo '<p><strong>' . $attribute_label . ':</strong> ' . $attribute_value . '</p>'; } } } else { echo '指定产品不存在'; }
关键说明
- 分类法slug调整:如果你的品牌属性slug不是
brand,需要将$brand_taxonomy的值改为pa_你的属性slug(比如属性slug是product-brand,则分类法为pa_product-brand),可在WooCommerce后台「产品 > 属性」中查看品牌属性的slug。 - 术语关联方式:
wp_set_object_terms的第四个参数设为true表示追加品牌,设为false会替换产品已有的所有品牌,可根据需求调整。 - 权限要求:执行该代码的用户需要拥有「编辑产品」和「管理产品属性」的权限,避免出现权限不足的错误。
内容的提问来源于stack exchange,提问作者sevoug
相关产品推荐
相关产品推荐

