在WordPress中如何通过别名获取WooCommerce属性标签与ID?
问题描述
我有一个WooCommerce产品属性:
- 名称(标签):Box Size
- 别名:box-size
尝试了以下代码查询该属性,但始终返回 Attribute not found: pa_box-size:
$attribute_slug = 'pa_box-size'; // Get the term object based on the attribute slug $term = get_term_by('slug', $attribute_slug, 'pa'); if ($term) { $attribute_label = $term->name; // Attribute label $attribute_id = $term->term_id; // Attribute ID // Output the attribute label and ID echo 'Attribute Slug: ' . $attribute_slug . '<br>'; echo 'Attribute Label: ' . $attribute_label . '<br>'; echo 'Attribute ID: ' . $attribute_id; } else { echo 'Attribute not found: ' . $attribute_slug; }
问题解决
错误原因
你混淆了WooCommerce产品属性的本质:产品属性本身是自定义分类法,而非某分类法下的术语(term)。你的代码用get_term_by去查询不存在的分类法pa下的术语pa_box-size,逻辑完全错误——WooCommerce的产品属性分类法命名规则是pa_{属性别名},比如你的属性别名是box-size,对应的分类法就是pa_box-size,而pa根本不是合法分类法。
正确代码(获取属性本身信息)
如果要获取属性的标签、WooCommerce内部ID等信息,应该用get_taxonomy()配合数据库查询:
$attribute_taxonomy = 'pa_box-size'; // 获取属性对应的自定义分类法对象 $taxonomy_obj = get_taxonomy($attribute_taxonomy); if ($taxonomy_obj) { $attribute_label = $taxonomy_obj->labels->singular_name; // 属性标签:Box Size echo '属性分类标识: ' . $attribute_taxonomy . '<br>'; echo '属性名称: ' . $attribute_label . '<br>'; // 获取WooCommerce属性表中的唯一ID(wp_woocommerce_attribute_taxonomies表的attribute_id) global $wpdb; $attribute_id = $wpdb->get_var( $wpdb->prepare( "SELECT attribute_id FROM {$wpdb->prefix}woocommerce_attribute_taxonomies WHERE attribute_name = %s", 'box-size' // 这里用属性别名,不带pa_前缀 ) ); echo 'WooCommerce属性ID: ' . $attribute_id; } else { echo '未找到属性分类: ' . $attribute_taxonomy; }
补充:如果要查询属性下的具体选项(术语)
如果你实际要找的是Box Size属性下的某个选项(比如"Small"),代码应该这样写:
$attribute_taxonomy = 'pa_box-size'; $term_slug = 'small'; // 选项的别名 $term = get_term_by('slug', $term_slug, $attribute_taxonomy); if ($term) { echo '选项名称: ' . $term->name . '<br>'; echo '选项ID: ' . $term->term_id; } else { echo '在属性 ' . $attribute_taxonomy . ' 下未找到该选项'; }
内容的提问来源于stack exchange,提问作者Zorro
相关产品推荐
相关产品推荐

