猫和子猫的Woocommerce订单购物车数组

时间:2020-01-31 15:30:50

标签: wordpress woocommerce

您好,我们正在尝试按主要产品类别对Woo购物车进行排序,并在该类别的产品下列出。如下所示:

车轮零件

  • 说话12
  • 轮胎的

框架

  • Y型车
  • X框架
  • Z框架

座位

  • 座位1
  • 座位2

我们设法按猫的顺序进行显示,但没有将它们订购到主猫->子猫中

我们有以下代码,并尝试按cat和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 );

请问有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您的代码是正确的,但是您只有natsort,返回1会引起问题。您还需要按菜单顺序对类别进行排序。请检查以下代码是否工作正常。

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

经过测试,效果很好

相关问题