我已经设法通过以下代码获取所有颜色属性:
$color_terms = get_terms(
array(
'taxonmy'=>'pa_color'
));
这适用于Shop页面,并返回所有颜色,但是如何将其限制为特定类别?可以说在“衬衫”类别中,我只有2种颜色,我只想显示这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文件中。经过测试和工作。
用法:
// 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循环访问每个term对象:
// 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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句