Home > other >  WooCommerce WC_Product::get_categories function is deprecated. Replace with wc_get_product_category_
WooCommerce WC_Product::get_categories function is deprecated. Replace with wc_get_product_category_

Time:01-30

I am trying to sort WooCommerce cart Products by Category, so it will be easier to pick the items since we have a pretty big warehouse and every order has an average of 50/60 different products.

This is the code we currently use:

add_action( 'woocommerce_cart_loaded_from_session', 'sort_cart_items_by_cat' );
   
    function sort_cart_items_by_cat() {
    $products_in_cart = array();
    foreach ( WC()->cart->get_cart_contents() as $key => $item ) {
    $products_in_cart[ $key ] = $item['data']->get_categories();
    }
 
    natsort( $products_in_cart );
 
    $cart_contents = array();
    foreach ( $products_in_cart as $cart_key => $product_category ) {
    $cart_contents[ $cart_key ] = WC()->cart->cart_contents[ $cart_key ];
}
    WC()->cart->cart_contents = $cart_contents;
}

The problem is that we get tons of PHP notices from WooCommerce. This is the PHP Notice we get about the deprecated function:

The WC_Product::get_categories function is deprecated since version 3.0. Replace with wc_get_product_category_list.

How should I modify the code correctly in order to use wc_get_product_category_list?

I already tried to replace get_categories with wc_get_product_category_list but problem persist.

Am I missing something?

CodePudding user response:

This should work. This is using the most current version of Woo.

function sort_cart_items_by_cat() {
    $products_in_cart = array();
    foreach ( WC()->cart->get_cart_contents() as $key => $item ) {

        $products_in_cart[ $key ] = wc_get_product_category_list( $item['product_id'] );
        
    }

    natsort( $products_in_cart );

    $cart_contents = array();
    foreach ( $products_in_cart as $cart_key => $product_category ) {
        $cart_contents[ $cart_key ] = WC()->cart->cart_contents[ $cart_key ];
    }
    WC()->cart->cart_contents = $cart_contents;
}
  •  Tags:  
  • Related