2015-09-13 233 views
0

的問題Woocommerce排序車產品按產品類別

我想使它所以我Woocommerce購物車顯示產品在產品類別的訂單。 (我的產品被分配到一個品牌,我想要的產品出現在車區域分配給他們的品牌之下。)

我已經試過

目前,我已經能夠得到它按字母順序排序,但是就我對數組的瞭解而言。

示例代碼

add_action('woocommerce_cart_loaded_from_session', function() { 

     global $woocommerce; 
     $products_in_cart = array(); 
     foreach ($woocommerce->cart->cart_contents as $key => $item) { 
      $products_in_cart[ $key ] = $item['data']->get_title(); 
     } 

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

其他注意事項

我知道我可以使用此代碼來獲取每個產品的術語ID。但我不太清楚如何最好地構造我的代碼來獲得我所追求的結果。

$terms = wp_get_post_terms(get_the_ID(), 'product_cat'); 

回答

2

你有所有正確的作品。

要獲得在這方面的帖子條款,你需要調整你是如何得到購物車中物品 $terms = wp_get_post_terms($item['data']->id, 'product_cat');

獲得這個職位方面會給你一個數組,看起來像這樣

的結果的ID
Array(
[0] => stdClass Object(
    [term_id] => 877 
    [name] => Product Category Name 
    [slug] => Product Category Name 
    [term_group] => 0 
    [term_taxonomy_id] => 714 
    [taxonomy] => product_cat 
    [description] => 
    [parent] => 0 
    [count] => 1 
    [filter] => raw 
    ) 
) 

下面的代碼將按照數組中的第一個類別對購物車進行排序。這並不完整,您需要考慮未設置的產品類別以及設置的多個產品類別。

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

你有什麼解決方案嗎? –