Display Categories Under Product Name at Cart in Woocommerce

I have setup Woocommerce and I have very similar product name but in different categories. For example, the product name “Class1” might appear twice but under different categories e.g. “Month1” and “Month2”. To make it more clear to users that they are buying the right product, I wanted to show the category of their selected product. I wanted to add category of each product and then possibly add it to the checkout page and cart too.

So, here is code. which you can add in your theme’s functions.php file of your active child theme (or theme).

add_filter( 'woocommerce_cart_item_name', 'wp_cart_item_category', 99, 3);
function wp_cart_item_category( $name, $cart_item, $cart_item_key ) {
$product_item = $cart_item['data'];
// make sure to get parent product if variation
if ( $product_item->is_type( 'variation' ) ) {
$product_item = wc_get_product( $product_item->get_parent_id() );
} 
$cat_ids = $product_item->get_category_ids();
// if product has categories, concatenate cart item name with them
if ( $cat_ids ) $name .= '
' . wc_get_product_category_list( $product_item->get_id(), ', ', '' . _n( 'Category:', 'Categories:', count( $cat_ids ), 'woocommerce' ) . ' ', '' ); return $name; }

Leave a Comment

Scroll to Top