How to sort items from a defined product category to be at the end of a cart order, for example I want all products that belong to a product category 'bottle' to be at the end of the cart order.
I have found this code that sorts by price, but would like to adjust to as described above.
add_action( 'woocommerce_cart_loaded_from_session', 'prefix_cart_order_prod_cat' );
function prefix_cart_order_prod_cat() {
$products_in_cart = array();
// Assign each product's price to its cart item key (to be used again later)
foreach ( WC()->cart->cart_contents as $key => $item ) {
$product = wc_get_product( $item['product_id'] );
$products_in_cart[ $key ] = $product->get_price();
}
// SORTING - use one or the other two following lines:
//asort( $products_in_cart ); // sort low to high
arsort( $products_in_cart ); // sort high to low
// Put sorted items back in cart
$cart_contents = array();
foreach ( $products_in_cart as $cart_key => $price ) {
$cart_contents[ $cart_key ] = WC()->cart->cart_contents[ $cart_key ];
}
WC()->cart->cart_contents = $cart_contents;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…