gpt4 book ai didi

php - 获取与 Woocommerce 中的产品类别相关的所有属性及其术语

转载 作者:行者123 更新时间:2023-12-04 01:25:51 25 4
gpt4 key购买 nike

众所周知,要获得添加到产品中的特定属性的术语,我们可以使用:

$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
)
)

关于php - 获取与 Woocommerce 中的产品类别相关的所有属性及其术语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52572687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com