Andy Tran

Ascending Sorting of Woocommerce Cart Items

Ascending Sorting of Woocommerce Cart Items

WooCommerce is the most popular eCommerce platform. It is a WordPress plugin that you can install and use to get starts with your online store. As you can see from the WooCommerce category, WooCommerce is a very flexible and customizable plugin that allows you to do a variety of things.

To customize WooCommerce, you must work with template files and may also use actions/hooks. So, if you want to customize your cart page, you can use WooCommerce actions/hooks. There are a plethora of WooCommerce actions/hooks that are specific to the various sections of the WooCommerce platform.

Using the WC()->cart

To get WooCommerce cart item data, use the WC()->cart method. This method is used on the cart page to load all of the values, such as cart item totals, subtotal,  cart items to count, items price, and more.

Sorting of Woocommerce Cart Items in Ascending Order

Products in WooCommerce are displayed graphically on the Cart Page or Checkout. However, some customers prefer a textual description on the cart page as well. So, if they are purchasing a large number of products or products that appear to be visually similar, they can easily cross-check them before confirming their order at the checkout.
There are many things displayed in Woocommerce Cart Items, Like – Product Name, Description, Quantity, and Sub Total. We can sort the product name in ascending order by following the below mentioned steps.

Before Sorting

Woocommerce Cart Items

  • Login to your WordPress Admin Dashboard.
  • From the sidebar,  Go to Appearance -> Theme Editor.
  • Go to functions.php file and write below code.

add_action( 'woocommerce_cart_loaded_from_session', 'sort_cart_items_alphabetically' );
function sort_cart_items_alphabetically() {
$products_in_cart = array();
foreach ( WC()->cart->get_cart_contents() as $key => $item ) {
$products_in_cart[ $key ] = $item['data']->get_title();
natsort( $products_in_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;

The above code should help you get the desired result of sorting the Product Name in ascending order as below.

After Sorting

Woocommerce Cart Items

WordPress Reference Links:

  1. How to reset your WordPress Site
  2. WhatsApp for WordPress


Submit a Comment

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