Home » WooCommerce: Sort Cart Items Alphabetically A>Z

WooCommerce: Sort Cart Items Alphabetically A>Z

by Tutor Aspire

Your WooCommerce shopping cart might look messy when it contains many products. Your specific business, besides, might require you buy “Part 1” first and “Part 2” after.

A way to tidy up the WooCommerce shopping basket is – for example – to sort products based on their title, from A to Z. As usual, this can be done with a few lines of PHP, even if you have no clue about coding… feel free to copy, paste, and enjoy the snippet 🙂

Sort WooCommerce Cart Products Alphabetically

PHP Snippet: Sort Products Alphabetically @ WooCommerce Cart

/**
* @snippet       Sort Products Alphabetically @ WooCommerce Cart
* @how-to        Get tutoraspire.com FREE
* @author        Tutor Aspire
* @testedwith    Woo 3.7
* @donate $9     https://www.tutoraspire.com
*/

add_action( 'woocommerce_cart_loaded_from_session', 'tutoraspire_sort_cart_items_alphabetically' );

function tutoraspire_sort_cart_items_alphabetically() {

// READ CART ITEMS
$products_in_cart = array();
foreach ( WC()->cart->get_cart_contents() as $key => $item ) {
$products_in_cart[ $key ] = $item['data']->get_title();
}

// SORT CART ITEMS
natsort( $products_in_cart );

// ASSIGN SORTED ITEMS TO CART
$cart_contents = array();
foreach ( $products_in_cart as $cart_key => $product_title ) {
$cart_contents[ $cart_key ] = WC()->cart->cart_contents[ $cart_key ];
}
WC()->cart->cart_contents = $cart_contents;

}

You may also like