WooCommerce Cart – Group Products By Category

I am trying to group my products in the woocommerce cart by category so that it display as

Category 1 – Product 1, Product 2.

Category 2 – Product 1, Product 2 etc

The loop in cart.php pulls through all products at the same time:

foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {

is there a way to only pull through products from one category? Something like:

foreach ( WC()->cart->get_cart(['product_cat']->'football') as $cart_item_key => $cart_item ) {

And then to repeat the loop again for each of the categories?

Thanks for the help – appreciated

1 Answer
1

You need to use has_term() conditional function inside the foreach loop like:

foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
    if( has_term( array('football'), 'product_cat', $cart_item['product_id'] ) ) {
        // Do something
    }
}

Leave a Comment