In WooCommerce, I’m currently building a function that will echo some product attributes in the shop page. I would like to separate these with commas if there is multiple attribute values available, but I don’t know how.
My code:
add_action('woocommerce_after_shop_loop_item_title', 'TitleVariations', 10);
function TitleVariations()
{
global $product;
$colormonth = $product->get_attribute('color-month');
$finish = $product->get_attribute('finish');
$design = $product->get_attribute('design');
echo '<span class="variation-display">';
echo __($colormonth, 'woocommerce');
echo __($finish, 'woocommerce');
echo __($crossdesign, 'woocommerce');
echo '</span>';
}
2
Answers
Collect your values to array and then
implode
this array:The WC_Product method
get_attribute()
gives a comma separated string of values when there is more than one value… You also need to check that each different attribute has at list one term…To get the product attribute label name, yo can use
wc_attribute_label()
product attribute function.1). If you want to get each product attribute with the label name and the term(s) value(s) (each different attribute in one line), you will use the following instead.
This code handle also custom product attributes:
2). But if you want to get all your product attributes terms as a comma separated string, your code will be something like in Display specific product attributes under product title in Woocommerce archive pages.
So for your code:
Code goes in functions.php file of the active child theme (or active theme). It should works.