How sort cart items by price – WooCommerce

Sometime is useful order the cart items by price.

For example, I needed to sort items of cart in a plugin that does discounts like ‘Buy 3 t-shirts get one free’. If there are three t-shirt on cart, the plugin applies the discount at the first t-short. Sorting by price the plugin applies the discount to the shirt cheapest.

The function is the callback of the hook woocommerce_cart_loaded_from_session of WooCommerce. When the the cart is recovered from the session, we collect the cart items in the array $cart sort. This array will be the element sorted by the function uasort.
This function sorts an array such that array indices maintain their correlation with the array elements they are associated with, using a user-defined comparison function.
In the example I used the function wpm_sort_by_price, to sort the array $cart_sort in ascending order. To sort in descending order you should use the function ‘wpm_sort_by_price_desc’.

Leave a comment

Your email address will not be published. Required fields are marked *