While working for a freelance client I had to “detect” the cart item categories in order to apply some PHP customization. So I thought – why not sharing with you how to display product categories in the Cart? This adds a nice touch to the Cart page 🙂

Also, I’m glad to introduce you to the amazing world of “wc_get_product_category_list“, a very handy WooCommerce PHP function!

Display product categories under each item in the WooCommerce Cart

PHP Snippet: Display Categories Under Product Name @ WooCommerce Cart


/**
 * @snippet       Display Categories Under Product Name @ WooCommerce Cart
 * @how-to        Get CustomizeWoo.com FREE
 * @sourcecode    https://businessbloomer.com/?p=72844
 * @author        Rodolfo Melogli
 * @testedwith    WooCommerce 3.2.1
 */

add_filter( 'woocommerce_cart_item_name', 'bbloomer_cart_item_category', 99, 3);

function bbloomer_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 .= '</br>' . wc_get_product_category_list( $product_item->get_id(), ', ', '<span class="posted_in">' . _n( 'Category:', 'Categories:', count( $cat_ids ), 'woocommerce' ) . ' ', '</span>' );

return $name;

}

Share:

Leave a Reply