繁体   English   中英

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

[英]Get all attributes with their terms related to a product category in 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
        )
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM