...
News, Tutorials, Wordpress

Sort Products in Cart by SKU in Woo Commerce

05 June 2017

you will need to add the following function to your functions.php file:

add_action( 'woocommerce_cart_loaded_from_session', function() {
 global $woocommerce;
 $products_in_cart = array();
 foreach ( $woocommerce->cart->cart_contents as $key => $item ) {
   $terms = get_post_meta( $item['data']->id, '_sku' );
   //$terms = wp_get_post_terms($item['data']->id, 'product_cat' );
   $products_in_cart[ $key ] = $terms[0];
 }

 asort( $products_in_cart , SORT_NUMERIC );

 $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 );

Leave a Comments


One Response to “Sort Products in Cart by SKU in Woo Commerce”

    • December 06 ,2018, at 8:23 PM Reply

      Hello, thanks for this code, it works but Could you help and show me how to make this work Descending cause for now it works Ascending.