我已经设法使用此代码获取所有颜色属性:
$color_terms = get_terms(
array(
'taxonmy'=>'pa_color'
));
这适用于Shop页面并返回所有颜色但是如何将其限制为某个类别?让我们说一个名为" Shirts"我只有2种颜色,我只想显示这两种颜色。
答案 0 :(得分:2)
尝试使用独特轻量级SQL查询的以下自定义函数:
function get_attribute_terms_in_product_cat( $category_term_name, $attribute_taxonomy ){
global $wpdb;
$terms = $wpdb->get_results( "SELECT DISTINCT t.*
FROM {$wpdb->prefix}terms as t
JOIN {$wpdb->prefix}term_taxonomy as tt ON tt.term_id = t.term_id
JOIN {$wpdb->prefix}term_relationships as tr ON tt.term_taxonomy_id = tr.term_taxonomy_id
WHERE tt.taxonomy LIKE '$attribute_taxonomy'
AND tr.object_id IN ( SELECT DISTINCT tr2.object_id
FROM {$wpdb->prefix}term_relationships as tr2
JOIN {$wpdb->prefix}term_taxonomy as tt2 ON tt2.term_taxonomy_id = tr2.term_taxonomy_id
JOIN {$wpdb->prefix}terms as t2 ON tt2.term_id = t2.term_id
WHERE tt2.taxonomy LIKE 'product_cat' AND t2.name = '$category_term_name'
)" );
return $terms;
}
代码放在活动子主题(或活动主题)的function.php文件中。经过测试和工作。
USAGE :
// Get the "pa_color" attribute terms for product category "Shirts"
$terms = get_attribute_terms_in_product_cat( "Shirts", "pa_color" );
此处"衬衫" 是产品类别术语名称," pa_color" 产品属性分类...
您将获得包含以下内容的产品属性值(术语对象)数组:
term_id
) name
) slug
) 您可以使用foreach循环访问每个术语对象:
// Get the "pa_color" attribute terms for product category "Shirts"
$terms = get_attribute_terms_in_product_cat( "Shirts", "pa_color" );
// Loop through each term
foreach( $terms as $term ){
$term_id = $term->term_id;
$term_name = $term->name;
$term_slug = $term->slug;
}