WooCommerce WC_Product::get_categories 功能已弃用。替换为 wc_get_product_category_list

WooCommerce WC_Product::get_categories function is deprecated. Replace with wc_get_product_category_list

我正在尝试按类别对 WooCommerce 购物车产品进行排序,这样会更容易挑选商品,因为我们有一个很大的仓库,每个订单平均有 50/60 种不同的产品。

这是我们目前使用的代码:

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

问题是我们从 WooCommerce 收到大量 PHP 通知。这是 PHP 我们得到的关于已弃用函数的通知:

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

如何正确修改代码才能使用wc_get_product_category_list?

我已经尝试用 wc_get_product_category_list 替换 get_categories 但问题仍然存在。

我是不是漏掉了什么?

这应该有效。这是使用最新版本的 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;
}