php - 获取与 Woocommerce 中产品类别相关的所有属性及其术语
问题描述
众所周知,要获取添加到产品中的特定属性的术语,我们可以使用:
$attr_terms = $product->get_attribute( 'attr_slug' );
或获取特定属性的所有术语,无论我们可以使用什么产品
$attr_terms = get_terms( 'pa_attr_slug' );
但是如何将所有属性及其术语添加到特定产品类别的产品中?
就像是:
$cat_attrs = ... ($cat->id);
foreach($cat_attrs as $cat_attr) {
echo $cat_attr->name; // name of attribute
foreach($cat_attr->terms as $term) {
echo $term->name; // name of attribute term
}
}
解决方案
要获取与产品类别相关的一系列产品属性分类法/术语名称,请尝试以下操作:
// Here define the product category SLUG
$category_slug = 'posters';
$query_args = array(
'status' => 'publish',
'limit' => -1,
'category' => array( $category_slug ),
);
$data = array();
foreach( wc_get_products($query_args) as $product ){
foreach( $product->get_attributes() as $taxonomy => $attribute ){
$attribute_name = wc_attribute_label( $taxonomy ); // Attribute name
// Or: $attribute_name = get_taxonomy( $taxonomy )->labels->singular_name;
foreach ( $attribute->get_terms() as $term ){
$data[$taxonomy][$term->term_id] = $term->name;
// Or with the product attribute label name instead:
// $data[$attribute_name][$term->term_id] = $term->name;
}
}
}
// Raw output (testing)
echo '<pre>'; print_r($data); echo '</pre>';
你会得到类似的东西(示例摘录):
Array
(
[pa_color] => Array
(
[9] => Blue
[10] => Green
)
[pa_size] => Array
(
[15] => Small
[16] => Medium
[18] => Large
)
)
推荐阅读
- asp.net-core - 来自 .bet core 3.1 webapi 的错误响应的全局定制
- python - 使用 NumPy 验证 Keras Conv2D 卷积返回不同层输出
- python - Python 标准库中容器的命名约定
- python - PyQt5 - 在表格小部件的列中创建一个检查项,即使行数与旋转框不同
- amazon-web-services - 具有自定义域路由的 AWS Cloudfront
- java - 如果用户已经存在,Firebase 登录应该转到主屏幕
- java - Java程序打印unicode值而不是字符串
- c++ - 在不打开文件的情况下打开 MultiDocTemplate
- azure - 无法通过 terraform 使用 oauth 创建 azure 广告应用程序
- sql - 仅当设置了 item 时才使用 WHERE 子句,否则选择所有行