Skip to content

Instantly share code, notes, and snippets.

@kreamweb
Last active September 12, 2022 22:31
Show Gist options
  • Save kreamweb/09e58bdb3c11cae5917b9bd7dae3e362 to your computer and use it in GitHub Desktop.
Save kreamweb/09e58bdb3c11cae5917b9bd7dae3e362 to your computer and use it in GitHub Desktop.
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();
}
@fadishaar7
Copy link

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' ) {

//if the cart is empty do nothing
if ( empty( WC()->cart->cart_contents ) ) {
	return;
}

//this is an array to collect cart items
$cart_sort = array();

//add cart item inside the array
foreach ( WC()->cart->cart_contents as $cart_item_key => $cart_item ) {
	$cart_sort[ $cart_item_key ] = WC()->cart->cart_contents[ $cart_item_key ];
}

//call the function to sort cart items
if ( $order == 'ASC' ) {
	@uasort( $cart_sort, 'wpm_sort_by_price' );
} else {
	@uasort( $cart_sort, 'wpm_sort_by_price_desc' );
}

//replace the cart contents with the array sorted
WC()->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