Woocommerce: Display Product Variation Description on Cart page

simplycity picture simplycity · Aug 19, 2016 · Viewed 19.4k times · Source

I'm trying to display my product variation description in my Cart. I have tried inserting this code in the cart.php template:

if ( $_product->is_type( 'variation' ) ) {echo $_product->get_variation_description();}

By following this documentation https://docs.woocommerce.com/document/template-structure/

But it's still not showing up.

Not sure what I'm doing wrong here.

Can anyone help on this?

Thanks

Answer

LoicTheAztec picture LoicTheAztec · Aug 19, 2016

UPDATE COMPATIBILITY for WooCommerce version 3+

Since WooCommerce 3, get_variation_description() is now deprecated and replaced by the WC_Product method get_description().

To get your product item variation description in cart (filtering variation product type condition), you have 2 possibilities (may be even more…):

  1. Displaying the variation description using woocommerce_cart_item_name hook, without editing any template.
  2. Displaying the variation description using the cart.php template.

In both cases you don't need to use in your code a foreach loop, as answered before, because it already exist. So the code will be more compact.

Case 1 - using woocommerce_cart_item_name hook:

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;
}

In this case the description is just displayed between the title and the variation attributes values.

This code goes in function.php file of your active child theme (or theme) or also in any plugin file.


Case 2 - Using cart/cart.php template (Update as per your comment).

You can chose where you want to display this description (2 choices):

  • After the title
  • After the title and the variation attributes values.

So you will insert this code on cart.php template around line 86 or 90 depending on your choice:

// Get the WC_Product
$product_item = $cart_item['data'];

if( ! empty( $product_item ) && $product_item->is_type( 'variation' ) ) {
    // WC 3+ compatibility
    $description = version_compare( WC_VERSION, '3.0', '<' ) ? $product_item->get_variation_description() : $product_item->get_description();
    if( ! empty( $description ) ) {
        // '<br>'. could be added optionally if needed
        echo  __( 'Description: ', 'woocommerce' ) . $description;;
    }
}

All the code is tested and is fully functional