如何获取WooCommerce产品属性术语的ID?
在WooCommerce中同时获取产品属性术语的ID与名称
get_attribute()方法确实只会返回术语名称的拼接字符串,要获取术语ID(以及完整的术语对象),你需要改用wc_get_product_terms()或者直接遍历产品的属性术语对象,下面是两种可行的实现方式:
方式一:指定单个属性分类法获取术语
如果你只需要处理名为Properties的属性,先确认它的分类法ID是pa_properties(WooCommerce自定义属性的分类法默认以pa_为前缀,后面跟属性的slug),然后用以下代码:
// 全局调用当前产品对象(产品页中可直接使用) global $product; // 目标属性的分类法ID $taxonomy = 'pa_properties'; // 获取当前产品关联的该属性所有术语对象 $attribute_terms = wc_get_product_terms( $product->get_id(), $taxonomy, array('fields' => 'all') // 指定返回完整术语对象,而非仅名称或ID ); // 遍历术语并输出信息 foreach ($attribute_terms as $term) { $term_id = $term->term_id; // 获取术语ID $term_name = $term->name; // 获取术语名称 $term_image = get_field('term_image', "{$taxonomy}_{$term_id}"); // 获取ACF图片字段(替换为你的字段名) // 前端输出示例(根据需求调整) echo '<div class="property-term">'; echo "<p>术语:{$term_name}(ID:{$term_id})</p>"; if ($term_image) { echo "<img src=\"{$term_image['url']}\" alt=\"{$term_name}\" />"; } echo '</div>'; }
方式二:遍历产品所有自定义属性
如果你需要处理产品的所有自定义属性,可以遍历get_attributes()返回的属性集合,跳过非分类法类型的属性(比如重量、尺寸这类默认属性):
global $product; // 获取产品所有属性 $product_attributes = $product->get_attributes(); foreach ($product_attributes as $taxonomy => $attribute) { // 跳过非自定义分类法属性 if (!$attribute->is_taxonomy()) { continue; } // 获取当前属性的术语对象 $terms = wc_get_product_terms( $product->get_id(), $taxonomy, array('fields' => 'all') ); foreach ($terms as $term) { $term_id = $term->term_id; $term_name = $term->name; $term_image = get_field('term_image', "{$taxonomy}_{$term_id}"); // 输出内容 echo '<div class="product-attribute">'; echo "<h4>{$term_name}(ID:{$term_id})</h4>"; if ($term_image) { echo "<img src=\"{$term_image['url']}\" alt=\"{$term_name}\" class=\"attribute-image\" />"; } echo '</div>'; } }
关键注意点:
- WooCommerce自定义属性的分类法ID必须以
pa_开头,比如属性名是Properties,对应的分类法slug是properties,所以分类法ID是pa_properties - ACF获取术语字段时,需要传入
{分类法ID}_{术语ID}作为参数,比如pa_properties_44,这样才能正确读取术语的自定义字段 - 使用
wc_get_product_terms()时,通过fields参数指定返回完整对象,才能获取ID、名称等所有数据
内容的提问来源于stack exchange,提问作者Kingsford
相关产品推荐
相关产品推荐

