2016-04-15 128 views
0

我想要做的就是製作一個foreach循環來獲取所有產品,並從這些產品中獲取他們的類別標識。這樣我可以稍後檢查某些類別。獲取WooCommerce中產品的類別標識

$order = new WC_Order($order_id); 
$items = $order->get_items(); 

foreach ($items as $item) { 
    $product_catagory_id .= $item['catagory_id']; //in between these brackets I need a value that gives me the catagory id. 
} 

//Some validation here if one of the catagorie_id's was found. 
//I can build this. It's not part of the question 

一些意見之後,這就是我滯留:

$order = new WC_Order($order_id); 
$items = $order->get_items(); 
foreach ($items as $item) { 
    $product_id = $item['product_id']; 
    var_dump($product_id); 
    $terms = get_the_term_list($product_id, 'term_id'); 
    var_dump($terms); 
} 

這將導致以下:

string(2) "79" 
object(WP_Error)#9148 (2) { 
    ["errors"]=> 
     array(1) { 
     ["invalid_taxonomy"]=> 
      array(1) { 
       [0]=> 
       string(19) "Ongeldige taxonomie" //invalid taxonomy 
      } 
     } 
    ["error_data"]=> 
    array(0) { 
    } 
} 

所以產品ID是完全讀取,我可以工作與此,但類別不能正確返回。

+1

put'var_dump($ item);退出;'在你的循環中,並告訴我們結果 – Unex

+0

這似乎並沒有工作,它給了我'無法修復格式不正確的JSON'在控制檯 –

+0

我的不好,刪除退出並記錄輸出給了我需要的結果。可悲的是沒有任何相關的catagory或catagory編號 –

回答

1

嘗試

$terms = get_the_terms ($product_id, 'product_cat'); 
foreach ($terms as $term) { 
    $cat_id = $term->id; 
} 

嘗試var_dump($terms);來正確地分析如何獲得類別ID。

希望這會有所幫助。

+0

如果您將'$ term-> id'編輯爲'$ tem-> term_id',您將得到類別ID的整數。 var_dump()會返回'int(x)',其中x是ID –

相關問題