Shehroz Ahmed
Shehroz Ahmed

Reputation: 537

Return product variation attribute values names (without hyphens)

to get Product Variations in WooCommerce, I'm using:

$product->get_available_variations();

But I'm getting results with hyphens, see this screenshot:

enter image description here

How can I get results without hyphens?

Thanks

Upvotes: 1

Views: 1155

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254117

Apparently, WooCommerce is displaying in this case, the attributes slugs values, then it replace spaces by hyphens and uppercase by lowercase, what is completely normal. So what you would like is to display the attributes names (and not the slugs).

For that you can use get_term_by( 'slug', $slug_value, $taxonomy ) to get first the object of values and then the name value...

1) You can check that get_term_by() function is really working with that code:

$term_value = get_term_by( 'slug', 'copper-stp-10100base-ttx', 'pa_sfp-module' );
echo $term_value->name; // will display the name value

2) Then your specific code is going to be:

$variations = $product->get_available_variations();

$attributes = $variations['attributes'];

// Iterating through each attribute in the array
foreach($attributes as $attribute => $slug_value){

    // Removing 'attribute_' from Product attribute slugs
    $term_attribute = str_replace('attribute_', '', $attribute);

    // Get the term object for the attribute value
    $attribute_value_object = get_term_by( 'slug', $slug_value, $term_attribute );

    // Get the attribute name value (instead of the slug)
    $attribute_name_value = $attribute_value_object->name

    // Displaying each attribute slug with his NAME value:
    echo 'Product attribute "' . $term_attribute . '" has as name value: ' . $attribute_name_value . '<br>';

}

This is tested and works.

Upvotes: 1

Related Questions