How to get all attributes with their terms related to specific Woocommerce product category [closed]

As we know, to get terms of specific attribute added to a product we can use:

$attr_terms = $product->get_attribute( 'attr_slug' );

OR to get all terms of specific attribute regardless of a product we can use

$attr_terms = get_terms( 'pa_attr_slug' );

But how to get all attributes with their terms added to products of specific product category?

Something like:

$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 Answer
1

Well, I found the following solution:

$args = array(
    'category'  => array( 'category_slug' )
    // or 'term_taxonomy_id' => 4 i.e. category ID
);

foreach( wc_get_products($args) as $product ){

    foreach( $product->get_attributes() as $attr_name => $attr ){

        echo wc_attribute_label( $attr_name ); // attr label
        // or get_taxonomy( $attr_name )->labels->singular_name;

        foreach( $attr->get_terms() as $term ){

            echo $term->name;
        }
    }
}

Leave a Comment