Skip to content

Instantly share code, notes, and snippets.

@maxrice

maxrice/gist:6541634

Last active Apr 23, 2020
Embed
What would you like to do?
WooCommerce - sort the cart alphabetically by the product's title
<?php
add_action( 'woocommerce_cart_loaded_from_session', function() {
global $woocommerce;
$products_in_cart = array();
foreach ( $woocommerce->cart->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 ] = $woocommerce->cart->cart_contents[ $cart_key ];
}
$woocommerce->cart->cart_contents = $cart_contents;
}, 100 );
@XiaoFaye

This comment has been minimized.

Copy link

@XiaoFaye XiaoFaye commented Jul 13, 2014

what if I want to sort by product taxonomy? can we do that?

@rilwis

This comment has been minimized.

Copy link

@rilwis rilwis commented Mar 18, 2015

This works perfectly. Thanks for sharing!

@adamsoleymani

This comment has been minimized.

Copy link

@adamsoleymani adamsoleymani commented Jan 23, 2017

Is there a way to sort it by the product order #?

Thanks,
Adam

@pavel-bondarchuk

This comment has been minimized.

Copy link

@pavel-bondarchuk pavel-bondarchuk commented Jul 20, 2017

hi
i want reorder by price low to hight
i replace get_title>get_price and product_title>product_price


add_action( 'woocommerce_cart_loaded_from_session', function() { global $woocommerce; $products_in_cart = array(); foreach ( $woocommerce->cart->cart_contents as $key => $item ) { $products_in_cart[ $key ] = $item['data']->**get_price**(); } natsort( $products_in_cart ); $cart_contents = array(); foreach ( $products_in_cart as $cart_key => $**product_price**) { $cart_contents[ $cart_key ] = $woocommerce->cart->cart_contents[ $cart_key ]; } $woocommerce->cart->cart_contents = $cart_contents; }, 100 );


work ok

if i want reorder price high to low - how rewrite code?

thanks

@kognito

This comment has been minimized.

Copy link

@kognito kognito commented Mar 19, 2018

Hi @pasharadio,

Did you resolve this by any chance?

Cheers
Clemens

@RegisStudio

This comment has been minimized.

Copy link

@RegisStudio RegisStudio commented Mar 28, 2018

@pasharadio,
Replace:
$woocommerce->cart->cart_contents = $cart_contents;
to:
$woocommerce->cart->cart_contents = array_reverse($cart_contents);

@selinrv

This comment has been minimized.

Copy link

@selinrv selinrv commented Dec 13, 2018

Is there a way to add all sort of ordering methods to cart page?

@parmarkartik19

This comment has been minimized.

Copy link

@parmarkartik19 parmarkartik19 commented Apr 23, 2020

Checkout Sort WooCommerce Products on Cart and Order plugin.

https://kartechify.com/product/sort-woocommerce-products-in-cart-and-order/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment