0

NOTE: This question was marked as similar to two other questions. This is incorrect, as those two other questions relate to displaying custom field data. I am not trying to do that. I simply want to display the name of the selected variation.

What I'd like to do is display the name of the selected variation under the product title, on the Cart, on the Order Confirmation page, and in the order email.

I'd like to achieve this with filters and functions, rather than creating a custom template files. I've done this a couple of years ago on another site. But can't recall the solution I used.

I've found numerous questions and answers related to this, but have been unsuccessful getting any of them to work. I suspect that is partly due to changes in WooCommerce. But even some more recent and updated answers are not working.

For example, this sounded close to what I wanted (it was for displaying variation name in the cart).

The answer provided used this code:

add_filter( 'woocommerce_cart_item_name', 'cart_variation_description', 20, 3);
function cart_variation_description( $name, $cart_item, $cart_item_key ) {
    // Get the corresponding WC_Product
    $product_item = $cart_item['data'];

    if(!empty($product_item) && $product_item->is_type( 'variation' ) ) {
        // WC 3+ compatibility
        $descrition = version_compare( WC_VERSION, '3.0', '<' ) ? $product_item->get_variation_description() : $product_item->get_description();
        $result = __( 'Description: ', 'woocommerce' ) . $descrition;
        return $name . '<br>' . $result;
    } else
        return $name;
}

Using this in the child theme 'functions.php', I found this had no effect at all.

I also tried the answer provided here. In that instance it was to display the brand attribute and categories. I swapped brand out for size (the name of my attribute/variation), but it had no output at all.

inspirednz
  • 4,807
  • 3
  • 22
  • 30

1 Answers1

0

Through the article here, I found I was able to achieve what I wanted with a very simple filter:

add_filter('woocommerce_add_cart_item_data','my_add_item_data',10,3);


function my_add_item_data($cart_item_data, $product_id, $variation_id)
{
if(isset($_REQUEST['size']))
{
$cart_item_data['size'] = sanitize_text_field($_REQUEST['size']);
}

return $cart_item_data;
}

This has added the variation info to cart, checkout confirmation, and the email. So simple!

inspirednz
  • 4,807
  • 3
  • 22
  • 30