Get the product attributes for variations from WooCommerce variable product

73 Views Asked by At

For a WC plugin I'm working on, I need to find the attribute that defines the variations of a product.

So, suppose we have a variable product that has attributes likes Color, Size, Material, but only "sizes" defines the variations. Then, I'd like an algorithm (I doubt there is a single WooCommerce method) to get the Size attribute (or its ID/slug).

Any help will be highly appreciated.

1

There are 1 best solutions below

0
LoicTheAztec On BEST ANSWER

You can use get_variation_attributes() method from a variable product like:

    global $product;

    $product = wc_get_product(15);

    if ( ! is_a($product, 'WC_Product') ) {
        $product = wc_get_product(get_the_ID);
    }

    if ($product->is_type('variable') ) {
        $output_html = '<ul class="variations-attributes">';

        foreach( $product->get_variation_attributes() as $attribute => $values ) {
            $label_name = wc_attribute_label( $attribute, $product );
            $term_names = $product->get_attribute($attribute);

            $output_html .= sprintf('<li>%s: %s</li>', $label_name, $term_names);
        }
        // Test output
        echo $output_html . '</ul>';
    }
}

Note that there are taxonomy attributes (for variations) and also custom attributes (for variations) not registered globally.

  • For taxonomy attributes, $attribute is the taxonomy and $values an array of term slugs.
  • For custom attributes, $attribute is the main attribute name and $values an array of values names.