2015-12-14 122 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');