I’m trying to add the attribute value names of a product attribute as classname for each item.
For example, I have a "Mood" attribute and the value names are "Happy", "Chill", "Energized", "Focused" and "Sleepy". I just need to wrap each of the attribute value names in a span tag and add the individual class like this:
Mood: <span class="attribute-chill">Chill</span> <span class="attribute-sleepy">Sleepy</span>
This is the code I have which displays the attributes, but I just need the css classes to be added.
add_action( 'woocommerce_after_shop_loop_item_title', 'display_applications_attribute_pa_mood', 5 );
function display_applications_attribute_pa_mood() {
global $product;
$mood = $product->get_attribute('pa_mood');
if ( $mood ) {
printf('<span class="attribute-mood">%1$s</span>', $mood );
}
}
2
Answers
Following the snippet on your post, since you’re simply aiming to retrieve the attribute values, you can directly collect the values from the product meta key _product_attributes. Please see the following snippet and see if it helps.
Hope this helps.
The following will, for specific defined product attributes, display each term name embedded in a
<span>
tag with the correct desired class property value:It should work as you expect.