Reputation: 103
The Problem
I would like to make it so my Woocommerce cart shows products in order of product category. (My products are assigned to a brand, and i want the products to appear in the cart area under their assigned brands.)
What I have tried
At the moment i've been able to get it to sort alphabetical by key however this is as far as my knowledge with arrays goes.
Example Code
add_action( 'woocommerce_cart_loaded_from_session', function() {
global $woocommerce;
$products_in_cart = array();
foreach ( $woocommerce->cart->cart_contents as $key => $item ) {
$products_in_cart[ $key ] = $item['data']->get_title();
}
ksort( $products_in_cart );
$cart_contents = array();
foreach ( $products_in_cart as $cart_key => $product_title ) {
$cart_contents[ $cart_key ] = $woocommerce->cart->cart_contents[ $cart_key ];
}
$woocommerce->cart->cart_contents = $cart_contents;
}, 100 );
Additional Notes
I know I can use this code to get the term ID of each product. But i'm not quite sure how best to structure my code to get the outcome I'm after.
$terms = wp_get_post_terms(get_the_ID(), 'product_cat' );
Upvotes: 0
Views: 2877
Reputation: 151
You've got all the right pieces.
To get the post terms in this context you need to tweak how you are getting the ID of the cart item
$terms = wp_get_post_terms($item['data']->id, 'product_cat' );
The result of getting the post terms will give you an array that looks like this
Array(
[0] => stdClass Object(
[term_id] => 877
[name] => Product Category Name
[slug] => Product Category Name
[term_group] => 0
[term_taxonomy_id] => 714
[taxonomy] => product_cat
[description] =>
[parent] => 0
[count] => 1
[filter] => raw
)
)
The code below will sort the cart by the first category in the array. This is not complete, you will need to account for no product category being set and also multiple product categories being set.
add_action( 'woocommerce_cart_loaded_from_session', function() {
global $woocommerce;
$products_in_cart = array();
foreach ( $woocommerce->cart->cart_contents as $key => $item ) {
$terms = wp_get_post_terms($item['data']->id, 'product_cat' );
$products_in_cart[ $key ] = $terms[0]->name;
}
ksort( $products_in_cart );
$cart_contents = array();
foreach ( $products_in_cart as $cart_key => $product_title ) {
$cart_contents[ $cart_key ] = $woocommerce->cart->cart_contents[ $cart_key ];
}
$woocommerce->cart->cart_contents = $cart_contents;
}, 100 );
Upvotes: 3