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

时间:2018-09-29 21:25:59

标签: php wordpress woocommerce product custom-taxonomy

我们知道,要获得添加到产品中的特定属性的字词,我们可以使用:

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

1 个答案:

答案 0 :(得分:2)

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

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