skip to Main Content

I am looking for a php snippet that sorts the woocommerce products according to sku in the mini cart/shopping cart, checkout page and thank you page.
The snippet below works well in the store but not for the rest.
Thank you in advance.

add_filter('woocommerce_get_catalog_ordering_args', 'am_woocommerce_catalog_orderby');
function am_woocommerce_catalog_orderby( $args ) {
    $args['meta_key'] = '_sku';
    $args['orderby'] = '_sku';
    $args['order'] = 'asc'; 
    return $args;
}

2

Answers


  1. Based on Sort WooCommerce cart items by vendor when using Dokan plugin, here is the way to sort cart items by SKU (works for cart items, mini-cart items and order items):

    add_action( 'woocommerce_cart_loaded_from_session', 'sort_cart_items_by_sku' );
    function sort_cart_items_by_sku( $cart ) {
        $items_to_sort = $cart_contents = array(); // Initializing
        
        // Loop through cart items
        foreach ( $cart->cart_contents as $item_key => $item ) {
            $items_to_sort[$item_key] = $item['data']->get_sku();
        }
        asort($items_to_sort); // sort items by sku
        
        // Loop through sorted items key
        foreach ( $items_to_sort as $key => $sku ) {
            $cart_contents[$key] = $cart->cart_contents[$key];
        }
        WC()->cart->cart_contents = $cart_contents; // Set sorted items as cart contents
    }
    

    Code goes in functions.php file of your active child theme (or active theme). Tested and work.

    Login or Signup to reply.
  2. Assuming Loic’s advice is solid (and I have no reason to doubt any of his contributions), this looks like a simple job for array_multisort().

    add_action('woocommerce_cart_loaded_from_session', 'sort_cart_items_by_sku');
    function sort_cart_items_by_sku($cart) {
        $skus = [];    
        foreach ($cart->cart_contents as $item ) {
            $skus[] = $item['data']->get_sku();  // populate sorting array of sku values
        }
        array_multisort($skus, $cart->cart_contents); // sort cart_contents by sku values
        WC()->cart->cart_contents = $cart->cart_contents; // Set sorted cart contents
    }
    

    Mocked-up demo: https://3v4l.org/YE75c

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search