Reputation: 33
how do you output variation attributes for an woocommerce product, where each attribute is in a seperate div?
add_action( 'woocommerce_after_shop_loop_item_title', 'display_color_attribute', 5 );
function display_color_attribute() {
global $product;
if ( $product->is_type('variable') ) {
$taxonomy = 'pa_color';
echo '<span class="attribute-color">' . $product->get_attribute($taxonomy) . '</span>';
}
}
This right here output both colors on the product page seperated by a comma so for one product it could be:
<span class="attribute-color">Black, Brown</span>
What i would like is to output these two colors in two seperate div, like this:
<span class="attribute-color black">Black</span>
<span class="attribute-color brown">Brown</span>
is this doable?
Upvotes: 2
Views: 1156
Reputation: 72269
1.By looking your code as well as based on get_attribute() details you are actually getting a comma separated string.
2.So explode()
it to convert to array and loop over it like below:
add_action( 'woocommerce_after_shop_loop_item_title', 'display_color_attribute', 5 );
function display_color_attribute() {
global $product;
if ( $product->is_type('variable') ) {
$taxonomy = 'pa_color';
$colors = explode(',',$product->get_attribute($taxonomy));
foreach ($colors as $color) {
echo '<span class="attribute-color '. strtolower(trim($color)) .'">' . trim($color) . '</span>';
}
}
}
Reference:-
Upvotes: 1
Reputation: 2338
I suspect $product->get_attribute($taxonomy);
returns an array so you would need to loop over it like below:
add_action( 'woocommerce_after_shop_loop_item_title', 'display_color_attribute', 5 );
function display_color_attribute() {
global $product;
if ( $product->is_type('variable') ) {
$taxonomy = 'pa_color';
$colors = $product->get_attribute($taxonomy);
foreach ($colors as $color) {
echo '<span class="attribute-color '. strtolower($color) .'">' . $color . '</span>';
}
}
}
Upvotes: 0