WooCommerce中如何按指定产品类别筛选颜色属性值
如何限定WooCommerce颜色属性仅显示特定产品类别下的选项
嘿,要实现仅展示“Shirts”类别下的颜色属性,我们需要先关联该类别下的产品,再提取这些产品对应的颜色术语,具体可以这么做:
方法一:通过WP_Query获取目标类别产品,再提取颜色属性
这个方法用WooCommerce/WP原生函数实现,兼容性更好:
// 1. 先获取"Shirts"产品类别的术语对象 $shirt_category = get_term_by('name', 'Shirts', 'product_cat'); // 检查类别是否存在 if ($shirt_category && !is_wp_error($shirt_category)) { // 2. 查询Shirts类别下的所有产品 $products_query = new WP_Query(array( 'post_type' => 'product', 'posts_per_page' => -1, // 获取所有产品 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => $shirt_category->term_id, 'operator' => 'IN' ) ), 'post_status' => 'publish' // 只取已发布的产品 )); // 3. 收集所有产品的颜色属性术语ID $color_term_ids = array(); if ($products_query->have_posts()) { while ($products_query->have_posts()) { $products_query->the_post(); global $product; // 获取当前产品的颜色属性术语 $product_colors = wp_get_post_terms(get_the_ID(), 'pa_color', array('fields' => 'ids')); if (!empty($product_colors)) { $color_term_ids = array_merge($color_term_ids, $product_colors); } } wp_reset_postdata(); // 重置查询 } // 4. 去重并获取唯一的颜色术语 $color_term_ids = array_unique($color_term_ids); if (!empty($color_term_ids)) { $color_terms = get_terms(array( 'taxonomy' => 'pa_color', 'include' => $color_term_ids, 'hide_empty' => false // 即使没有产品使用也显示(可选,根据需求调整) )); } else { $color_terms = array(); // 如果该类别下没有颜色属性,返回空数组 } } else { // 如果Shirts类别不存在,返回空数组或提示 $color_terms = array(); } // 现在$color_terms就是Shirts类别下的所有颜色属性了 foreach ($color_terms as $color) { echo $color->name . '<br>'; }
方法二:直接用SQL查询(更高效,适合产品较多的场景)
如果你的商店产品数量很大,上面的方法可能有点慢,可以用直接查询数据库的方式,避免循环产品:
global $wpdb; // 获取Shirts类别的term_id $shirt_term_id = $wpdb->get_var($wpdb->prepare( "SELECT term_id FROM $wpdb->terms WHERE name = %s AND taxonomy = 'product_cat'", 'Shirts' )); if ($shirt_term_id) { // 查询关联Shirts类别且有pa_color属性的术语ID $color_term_ids = $wpdb->get_col($wpdb->prepare( "SELECT DISTINCT tr2.term_id FROM $wpdb->term_relationships tr1 JOIN $wpdb->term_relationships tr2 ON tr1.object_id = tr2.object_id WHERE tr1.term_taxonomy_id = (SELECT term_taxonomy_id FROM $wpdb->term_taxonomy WHERE term_id = %d AND taxonomy = 'product_cat') AND tr2.term_taxonomy_id IN (SELECT term_taxonomy_id FROM $wpdb->term_taxonomy WHERE taxonomy = 'pa_color')", $shirt_term_id )); if (!empty($color_term_ids)) { $color_terms = get_terms(array( 'taxonomy' => 'pa_color', 'include' => $color_term_ids, 'hide_empty' => false )); } else { $color_terms = array(); } } else { $color_terms = array(); }
注意事项
- 如果你知道Shirts类别的slug或者ID,可以直接替换
get_term_by的参数,比如用slug的话:get_term_by('slug', 'shirts', 'product_cat'),这样更稳定(名称可能会修改)。 hide_empty参数如果设为true,会只显示该类别下有产品在使用的颜色;设为false则会显示所有关联过该类别产品的颜色,即使现在没有产品在用了,可根据你的需求调整。
内容的提问来源于stack exchange,提问作者user7432810
相关产品推荐
相关产品推荐

