One Hour
One Hour

Reputation: 17

Woocommerce Cart - Sort by Category

I need help. I want to sort prodyct in my cart page by category like this:

Category1

Category2

Category3

I found this code but it is working strange. For some products it is sorting OK, but for other - no. Could you help me?

add_action( 'woocommerce_cart_loaded_from_session', function() {

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

    ksort( $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 );```

Upvotes: 0

Views: 341

Answers (1)

Jan Ranostaj
Jan Ranostaj

Reputation: 146

You also need to set new cart session and you can also utilize $cart property passed into action:

( Although I have not tested this idea please try )

add_action( 'woocommerce_cart_loaded_from_session', function($cart) {

   $products_in_cart = array();

   foreach ( $cart->get_cart() as $key => $item ) {
       $terms = wp_get_post_terms($item['data']->get_id(), 'product_cat' );
       $products_in_cart[ $key ] = $terms[0]->name;
   }

   asort( $products_in_cart );

   $cart_contents = array();
   foreach ( $products_in_cart as $cart_key => $product_title ) {
       $cart_contents[ $cart_key ] = $cart->cart_contents[ $cart_key ];
   }

   $cart->set_cart_contents($cart_contents);
   $cart->set_session();

}, 100, 1 );

Upvotes: 1

Related Questions