Create a gist now

Instantly share code, notes, and snippets.

Woocommerce - Sort cart items by price
add_action( 'woocommerce_cart_loaded_from_session', 'wpm_cart_order_items_by_price' );
function wpm_cart_order_items_by_price( $cart ) {
//if the cart is empty do nothing
if ( empty( $cart->cart_contents ) ) {
return;
}
//this is an array to collect cart items
$cart_sort = array();
//add cart item inside the array
foreach ( $cart->cart_contents as $cart_item_key => $cart_item ) {
$cart_sort[ $cart_item_key ] = $cart->cart_contents[ $cart_item_key ];
}
//call the function to sort cart items
@uasort( $cart_sort, 'wpm_sort_by_price' );
//replace the cart contents with the array sorted
$cart->cart_contents = $cart_sort;
}
function wpm_sort_by_price( $cart_item_a, $cart_item_b ) {
return $cart_item_a['data']->get_price() > $cart_item_b['data']->get_price();
}
function wpm_sort_by_price_desc( $cart_item_a, $cart_item_b ) {
return $cart_item_a['data']->get_price() < $cart_item_b['data']->get_price();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment