Last active
September 12, 2022 22:31
-
-
Save kreamweb/09e58bdb3c11cae5917b9bd7dae3e362 to your computer and use it in GitHub Desktop.
Woocommerce - Sort cart items by price
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
thanks for the code. but if i need it to be ASC what a need to modify ? i used another code for you as below : is it working fine ??
add_action( 'woocommerce_cart_loaded_from_session', 'wpm_cart_order_items_by_price' );
function wpm_cart_order_items_by_price( $order = 'ASC' ) {
}
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();
}