This page looks best with JavaScript enabled

How to Sort Woocommerce Cart Items Alphabetically

 ·  โ˜• 1 min read  ·  ๐Ÿ‘ฝ john hashim

If youโ€™re running a woo-commerce online shop site with a lot of Products and you would like to make it easier for your customers to be able to check what they have in their cart without so many downs then using this snippet of code would be your best choice.

if youโ€™re creating a pluging or a new theme then this can be added in the functions.php and if your using a child theme then you can easily create functions.php files in your child them then add the code.

NB: dont do this on a production site always use an online snippet on your local or staging site to avoid errors and down

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
add_action( 'woocommerce_cart_loaded_from_session', 'wooc_sort_cart_items_alphabetically' );
 
function wooc_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;
 
}
?>

thanks for stopping by!!! ๐Ÿ˜‰

Share on

john hashim
WRITTEN BY
john hashim
Web Developer