Woocommerce编程为指定分类下所有产品批量添加color属性的方法
WooCommerce指定分类产品批量添加color属性解决方案
以下是调整完成可直接使用的代码,已修复原代码会覆盖产品已有属性的问题,新增了目标分类产品自动遍历逻辑:
// 替换为你要操作的X产品分类的别名 $target_category_slug = 'your-target-category-slug'; // 查询目标分类下的所有已发布产品 $args = array( 'post_type' => 'product', 'posts_per_page' => -1, 'post_status' => 'publish', 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'slug', 'terms' => $target_category_slug, ) ) ); $products = new WP_Query($args); if ($products->have_posts()) { while ($products->have_posts()) { $products->the_post(); $product_id = get_the_ID(); // 绑定color属性值到产品 wp_set_object_terms($product_id, 'black', 'pa_color', true); // 读取产品现有属性,避免覆盖原有属性(比如尺寸、重量等) $existing_attributes = get_post_meta($product_id, '_product_attributes', true); if (empty($existing_attributes)) { $existing_attributes = array(); } // 合并color属性到现有属性数组 $existing_attributes['pa_color'] = array( 'name' => 'pa_color', 'value' => 'black', 'is_visible' => '1', 'is_taxonomy' => '1' ); // 更新产品属性元数据 update_post_meta($product_id, '_product_attributes', $existing_attributes); } wp_reset_postdata(); }
使用说明
- 操作前请先备份站点数据库,避免误操作导致数据丢失
- 先到WooCommerce后台「产品-属性」页确认
pa_color全局属性已创建,再执行代码 - 如果要按分类ID筛选产品,将
tax_query中的field参数改为term_id,terms参数填分类ID即可 - 将代码添加到当前主题的
functions.php文件,或者根目录新建临时PHP文件写入代码,访问一次触发执行,完成后立即删除代码,避免重复执行 - 若需要设置的color值不是
black,替换代码中所有对应位置的black字符串即可
内容的提问来源于stack exchange,提问作者yasin taqizade
相关产品推荐
相关产品推荐

