2015-12-14 121 views
0

我試圖在產品頁面中使用產品ID獲取主類別ID,但沒有成功。Woocommerce來自產品ID的產品類別ID

請幫忙: - |

我知道,如果產品是從X類和手動更改價格

+0

你是什麼意思,「手動更改價格」,你想設置該類別的折扣? – Firefog

回答

0

下面是一個例子得到從產品ID宇商貿類ID

GET類別產品頁面

global $post; 
$terms = get_the_terms($post->ID, 'product_cat'); 
foreach ($terms as $term) { 
    $product_cat_id = $term->term_id; 
    break; 
} 
+0

謝謝,那完美的工作:-) –

+0

@GilJosef如果答案幫助你嘗試接受它,並放棄投票..乾杯 – Firefog

0

一般來說:

/** 
* Get products categories given a product ID. 
* 
* @author Nabil Kadimi 
* @link https://stackoverflow.com/a/46714456/358906 
* 
* @param Integer $product_id The product ID. 
* @param String $fields  Which fields to retrieve all, ids, names, 
*        count, id=>parent, id=>slug or id=>name. 
*        See WP_Term_Query constructor for more info. 
* @return Array    The categories. 
*/ 
function so34274948_wc_get_categories_by_product_id($product_id, $fields) { 
    return wp_get_post_terms($product_id, 'product_cat', [ 'fields' => $fields ]); 
} 

例如:

$categories = so34274948_wc_get_categories_by_product_id(123, 'ids');