Woocommerce购物车-按类别排序

时间:2020-04-14 13:41:51

标签: wordpress woocommerce

我需要帮助。我想按以下类别对购物车页面中的产品进行排序:

Category1

  • 产品1
  • Product2
  • Product3

Category2

  • 产品1
  • Product2
  • Product3

Category3

  • 产品1
  • Product2
  • Product3

我找到了此代码,但它的工作方式很奇怪。对于某些产品,它排序还可以,但对于其他产品-否。你能帮我吗?

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

1 个答案:

答案 0 :(得分:1)

您还需要设置新的购物车会话,还可以利用已生效的$cart属性:

(尽管我还没有测试过这个想法,请尝试)

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