Get the product attribute label name in Woocommerce 3
Asked Answered
F

1

7

I am using a lot of product attributes on my products in Woocommerce and I am looping through all variations in a table that can be displayed with a shortcode on a product page.

For this table I need all the product attributes in the table head (this is before looping through the variations) and I get the attributes using:

$attributes = $product->get_variation_attributes();
foreach ($attributes as $key => $value) {
    echo '<td>'.&key.'</td>';
}

This isn't very elegant, is it?

So this works, too:

$attributes = $product->get_attributes();
foreach ($attributes as $attribute) {
    echo '<td>'$attribute['name']'</td>';
}

In both cases I get the slug of the product attribute. I need to get the label name instead, since there is a Polylang translation for each name (terms also).

How can I get the product attribute label name instead of the taxonomy slug?

Forego answered 31/10, 2018 at 9:14 Comment(2)
Try and "var_dump" the "$attributes" object. May be that will give you some idea of which attribute of the "$attributes" object need to be used in the loop.Undertow
Thank you. Helpful for me to understanding more of what is going on here. Unfortunately, there is no name to get within the arrays, just the slug. I tried it for both blocks of code. The arrays I get when using the second method contain id, position, variation ... but still no actual name.Forego
F
14

You will use wc_attribute_label() dedicated Woocommerce function:

foreach ($product->get_variation_attributes() as $taxonomy => $term_names ) {
    // Get the attribute label
    $attribute_label_name = wc_attribute_label($taxonomy);

    // Display attribute labe name
    echo '<td>'.$attribute_label_name.'</td>';
}

OR:

foreach ($product->get_attributes() as $taxonomy => $attribute_obj ) {
    // Get the attribute label
    $attribute_label_name = wc_attribute_label($taxonomy);

    // Display attribute labe name
    echo '<td>'.$attribute_label_name.'</td>';
}
Fribble answered 31/10, 2018 at 10:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.