I\'m trying to display my product variation description in my Cart. I have tried inserting this code in the cart.php
template:
This will work for WC 3.0
add_filter( 'woocommerce_cart_item_name', 'cart_variation_description', 20, 3);
function cart_variation_description( $title, $cart_item, $cart_item_key ) {
$item = $cart_item['data'];
if(!empty($item) && $item->is_type( 'variation' ) ) {
return $item->get_name();
} else
return $title;
}
You can get it via global variable $woocommerce
also-
global $woocommerce;
$cart_data = $woocommerce->cart->get_cart();
foreach ($cart_data as $value) {
$_product = $value['data'];
if( $_product->is_type( 'variation' ) ){
echo $_product->id . '<br>';
}
}
I already check it.
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…):
woocommerce_cart_item_name
hook, without editing any 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):
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