Show the attribute name beside the attribute value in WooCommerce (in Cart, Checkout and order emails).
When a variable product with a single attribute is added to the cart the attribute name (e.g. Size or Colour etc) is not shown, only the value (e.g. Medium or Large etc). If the product has multiple attributes then the attribute name and value are shown. This is to prevent any confusion as to what each value is for.
I quite enjoy questions like this as it brings out the code detective in me. I fired up my local development environment (XAMPP on Windows with Visual Studio Code for source level debugging if required) and began looking at the WooCommerce email template files. The woocommerce/templates/emails/email-order-items.php file looked promising as it looped through the order items and had call to a wc_display_item_meta() function.
I did an experiment with the actions that were before and after the call to wc_display_item_meta(), ‘woocommerce_order_item_meta_start‘ and ‘woocommerce_order_item_meta_end‘. An experiment with a product with two attributes had the attributes and values output by the wc_display_item_meta() function. The problem was that, for a product with a single attribute, the attribute value (not name) was output before the actions.
I did some source level debugging and found that the call to $item->get_name() returned both the product name and attribute value. Mmm, strange.
A bit of luck
Somehow I eventually found the function that appended the attribute value to the product name – WC_Product_Variation_Data_Store_CPT::generate_product_title() in woocommerce/includes/data-stores/class-wc-product-variation-data-store-cpt.php.
I do not remember how I found this function. Maybe I searched for ‘ – ‘ and examined each of the 8 files that had that string.
I experimented with the filters in that function and found that ‘woocommerce_product_variation_title_include_attributes‘ was the one I needed. Simply returning false caused the attribute name and value to be shown in the cart, checkout and in the order emails.
Before and After screenshots
Here’s the default Cart. The product with two attributes (Long Sleeve Tee) has the attribute names (Size and Collar Colour) shown. The Tshirt product only has a single attribute (Colour) so only the chosen value (Green) is shown.
Once my code is active then both products have the attribute name and value shown.
For the Checkout the default is same – no attribute name for the product with a single attribute.
And the attribute name and value are shown for both products when my code is active.
Finally, the New Order email before screenshot: