Sort WooCommerce products in cart order by price
By default the WooCommerce cart is ordered by when products are ordered in sequence, this can be manipulated with the woocommerce_cart_loaded_from_session hook.
A new array is created $products_in_cart and the carts content is looped with the key of the array being the price $product->get_price(), the array is then sorted with asort or arsort before being put back in a new array.
add_action( 'woocommerce_cart_loaded_from_session', 'prefix_cart_order_prod_cat' ); /** * WooCommerce - sort cart order by price * @link https://stackoverflow.com/questions/17194899/woocommerce-cart-page-display-products-order-by-product-price/57136404#57136404 */ 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; }
The above will sort from high to low, to reverse the sort from low to high comment out the sorting options in the code snippet.
This Code does not work for up to date woocommerce with mini-cart .. seems to make very strange calculations for the prices!