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?

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Renato
  • 73
  • 1
  • 1
  • 5
  • 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. – zipkundan Oct 31 '18 at 09:43
  • 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. – Renato Oct 31 '18 at 10:20

1 Answers1

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>';
}
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399