use*_*810 1 php wordpress product custom-taxonomy woocommerce
我已经设法使用此代码获取所有颜色属性:
$color_terms = get_terms(
array(
'taxonmy'=>'pa_color'
));
Run Code Online (Sandbox Code Playgroud)
这适用于商店页面并返回所有颜色,但如何将其限制为特定类别?假设在名为“衬衫”的类别中我只有 2 种颜色,并且我只想显示这 2 种颜色。
尝试以下使用独特的轻型 SQL 查询的自定义函数:
\n\nfunction get_attribute_terms_in_product_cat( $category_term_name, $attribute_taxonomy ){\n global $wpdb;\n\n $terms = $wpdb->get_results( "SELECT DISTINCT t.*\n FROM {$wpdb->prefix}terms as t\n JOIN {$wpdb->prefix}term_taxonomy as tt ON tt.term_id = t.term_id\n JOIN {$wpdb->prefix}term_relationships as tr ON tt.term_taxonomy_id = tr.term_taxonomy_id\n WHERE tt.taxonomy LIKE \'$attribute_taxonomy\'\n AND tr.object_id IN ( SELECT DISTINCT tr2.object_id\n FROM {$wpdb->prefix}term_relationships as tr2\n JOIN {$wpdb->prefix}term_taxonomy as tt2 ON tt2.term_taxonomy_id = tr2.term_taxonomy_id\n JOIN {$wpdb->prefix}terms as t2 ON tt2.term_id = t2.term_id\n WHERE tt2.taxonomy LIKE \'product_cat\' AND t2.name = \'$category_term_name\'\n )" );\n\n return $terms;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n代码位于活动子主题(或活动主题)的 function.php 文件中。经过测试并有效。
\n\n用法:
\n\n// Get the "pa_color" attribute terms for product category "Shirts"\n$terms = get_attribute_terms_in_product_cat( "Shirts", "pa_color" );\n
Run Code Online (Sandbox Code Playgroud)\n\n这里“Shirts”是产品类别术语名称,“pa_color”是产品属性分类\xe2\x80\xa6
\n\n您将获得一个产品属性值(术语对象)数组,其中包含:
\n\nterm_id
) name
)slug
)您可以使用 foreach 循环来访问每个术语对象:
\n\n// Get the "pa_color" attribute terms for product category "Shirts"\n$terms = get_attribute_terms_in_product_cat( "Shirts", "pa_color" );\n\n// Loop through each term\nforeach( $terms as $term ){\n $term_id = $term->term_id;\n $term_name = $term->name;\n $term_slug = $term->slug;\n}\n
Run Code Online (Sandbox Code Playgroud)\n
归档时间: |
|
查看次数: |
2471 次 |
最近记录: |