如何在Woocommerce中为不同分类的新产品自动添加对应属性?
WooCommerce 按商品分类自动添加对应属性
要实现添加新产品时根据所属分类自动添加指定属性,可通过以下代码实现,核心是利用WooCommerce的产品保存钩子触发属性添加逻辑:
代码实现
将以下代码添加到你的主题functions.php文件或自定义插件中:
add_action('woocommerce_admin_process_product_object', 'auto_add_attributes_by_category'); function auto_add_attributes_by_category($product) { // 定义分类与对应属性的映射关系 $category_attr_map = array( '处理器' => array('属性A', '属性B', '属性C'), // 替换为你的分类slug和属性名称 '主板' => array('属性D', '属性E', '属性F') ); // 获取产品所属的所有分类slug $product_categories = wp_list_pluck(wp_get_post_terms($product->get_id(), 'product_cat'), 'slug'); // 遍历映射关系,匹配分类后添加属性 foreach ($category_attr_map as $cat_slug => $attributes) { if (in_array($cat_slug, $product_categories)) { foreach ($attributes as $attr_name) { // 获取属性ID(需确保属性已在后台创建) $attr_id = wc_attribute_taxonomy_id_by_name($attr_name); if (!$attr_id) continue; $attr_taxonomy = 'pa_' . $attr_name; // 属性的分类法名称 // 检查属性是否已存在,避免重复添加 $existing_attrs = $product->get_attributes(); if (!isset($existing_attrs[$attr_taxonomy])) { // 创建属性对象并添加到产品 $attribute = new WC_Product_Attribute(); $attribute->set_id($attr_id); $attribute->set_name($attr_taxonomy); $attribute->set_options(array()); // 若需要预设选项可在这里添加 $attribute->set_position(0); $attribute->set_visible(true); $attribute->set_variation(false); // 若要作为变体属性,设为true $existing_attrs[$attr_taxonomy] = $attribute; $product->set_attributes($existing_attrs); } } } } }
注意事项
- 提前在WooCommerce后台产品 > 属性中创建好所有需要自动添加的属性(如属性A、属性B等),否则代码无法找到对应属性ID,无法完成添加。
- 代码中的
处理器、主板是分类的slug,需替换为你实际使用的分类slug(可在分类编辑页面查看)。 - 若需要让属性作为产品变体的选项,将
set_variation(false)改为set_variation(true)即可。 - 测试时,新建产品并选择对应分类,保存后进入产品编辑页面的“属性”标签,即可看到自动添加的属性。
内容的提问来源于stack exchange,提问作者Osama Alrefai
相关产品推荐
相关产品推荐

