Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Woocommerce Order cart array by cat and sub cat

Hi we are trying to sort the Woo Cart by Main product category and list under the products in that category. Like below:

Wheel Parts

  • spokes 12
  • Tyre's

Frame

  • Y Frame
  • X Frame
  • Z Frame

Seat

  • Seat 1
  • Seat 2

We have managed to get to display by cat order but it is not ordering them into Main Cat -> Sub Cat

We have the below code and trying to order cart array by cat and sub cat

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;
    }

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

Any one have any ideas please?

like image 936
John Jones Avatar asked Jan 31 '20 15:01

John Jones


1 Answers

Your code was correct but you had just natsort which returning 1 is causing the issue. You also need to sort categories by menu order. Please check the below code working perfectly.

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]->term_id;
    }
    // $categories = get_terms( 'product_cat', 'orderby=menu_order&hide_empty=1' );

    asort($products_in_cart);
    $cat_array = array();
    foreach ($products_in_cart as $key => $value) {
        $cat_array[$key] =get_term_by('id', $value, 'product_cat');
    }
    $mai_cat = [];
    $i=0;
    foreach ($cat_array as $parent_key => $parent_value) {
        if($parent_value->parent == 0)
        {
            $mai_cat[$parent_key] = $parent_value->term_id;
            foreach ($cat_array as $parent_key_sub => $parent_value_sub) {
                if($parent_value_sub->parent == $parent_value->term_id)
                {
                    $mai_cat[$parent_key_sub] = $parent_value_sub->term_id;
                }
            }   
        }
    }
    $cart_contents = array();
    foreach ( $mai_cat as $cart_key => $product_title ) {
        $cart_contents[ $cart_key ] = $woocommerce->cart->cart_contents[ $cart_key ];

    }
    $woocommerce->cart->cart_contents = $cart_contents;
}, 100 );

Tested and works well

like image 119
raju_odi Avatar answered Nov 19 '22 12:11

raju_odi