首页 > 解决方案 > 获取与 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
    }
}

标签: phpwordpresswoocommerceproductcustom-taxonomy

解决方案


要获取与产品类别相关的一系列产品属性分类法/术语名称,请尝试以下操作:

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

推荐阅读