phpwordpresswoocommerceproductcustom-taxonomy

Get all attributes with their terms related to a product category in Woocommerce


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

Solution

  • To get an array of product attributes taxonomies/term names related to a product category, try the following:

    // 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>';
    

    You will get something like (an example extract):

    Array
    (
        [pa_color] => Array
            (
                [9]  => Blue
                [10] => Green
            )
        [pa_size] => Array
            (
                [15] => Small
                [16] => Medium
                [18] => Large
            )
    )