You can use has_term()
conditional WordPress function to check if cart items belongs to a product category (but the defined category(ies) need to be set for the related products (items)).
So the following code will sort cart items with items belonging to specified category(ies) at the end:
add_action( 'woocommerce_cart_loaded_from_session', 'product_category_cart_items_sorted_end' );
function product_category_cart_items_sorted_end() {
$category_terms = __('T-shirts'); // Here set your category terms (can be names, slugs or Ids)
$items_in_category = $other_items = array(); // Initizlizing
// Assign each item in a different array depending if it belongs to defined category terms or not
foreach ( WC()->cart->cart_contents as $key => $item ) {
if( has_term( $category_terms, 'product_cat', $item['product_id'] ) ) {
$items_in_category[ $key ] = $item;
} else {
$other_items[ $key ] = $item;
}
}
// Set back merged items arrays with the items that belongs to a category at the end
WC()->cart->cart_contents = array_merge( $other_items, $items_in_category );
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…