How sort cart items by price – WooCommerce

Sometimes is useful order the cart items by price.

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

The function wpm_cart_order_items_by_price is the callback of the WooCommerce hook woocommerce_cart_loaded_from_session.

When 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 Reply

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

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.