如何获取WooCommerce属性术语ID以调用term_description?
在WooCommerce中获取商品属性术语ID并显示描述
核心思路
WooCommerce的商品属性属于自定义分类法,格式为pa_属性slug(比如属性“颜色”对应分类法pa_color)。要获取术语ID,需结合属性分类法与术语名称,或直接获取商品关联的属性术语对象。
方案1:已知属性分类法时,通过术语名称获取ID
如果明确要处理的属性(比如“尺码”),先通过get_attribute拿到术语名称,再用get_term_by匹配分类法获取ID:
global $product; // 替换为你的属性显示名称(比如"尺码") $attribute_name = '尺码'; // 对应属性的分类法slug(必须以pa_开头,比如pa_size) $taxonomy = 'pa_size'; // 获取商品的该属性术语名称 $term_name = $product->get_attribute($attribute_name); // 处理多术语情况(逗号分隔) $term_names = explode(', ', $term_name); foreach ($term_names as $name) { $name = trim($name); // 通过名称和分类法获取术语对象 $term = get_term_by('name', $name, $taxonomy); if ($term && !is_wp_error($term)) { // 获取术语ID并输出描述 echo '<div class="term-description">' . term_description($term->term_id, $taxonomy) . '</div>'; } }
方案2:动态遍历商品所有属性术语(无需硬编码)
如果要批量处理商品的所有可见属性,直接获取商品的属性集合,遍历每个属性的术语对象:
global $product; // 获取商品的所有属性(包含术语数据) $attributes = $product->get_attributes(); foreach ($attributes as $attribute) { // 跳过不可见的属性(可选) if (!$attribute->get_visible()) continue; $taxonomy = $attribute->get_taxonomy(); // 获取该商品关联的当前属性术语 $terms = wc_get_product_terms($product->get_id(), $taxonomy, ['fields' => 'all']); foreach ($terms as $term) { // 输出术语名称和对应描述 echo '<div class="attribute-term"> <h4>' . $term->name . '</h4> <p>' . term_description($term->term_id, $taxonomy) . '</p> </div>'; } }
常见问题排查
- 之前
get_terms无效?因为get_terms是获取整个分类法的所有术语,而非当前商品关联的术语,改用wc_get_product_terms即可精准获取商品绑定的属性术语。 - 分类法slug错误?必须以
pa_开头,比如属性“材质”的slug是material,分类法就是pa_material,可在WooCommerce后台“产品>属性”中查看属性slug。
内容的提问来源于stack exchange,提问作者Nams
相关产品推荐
相关产品推荐

