How to get the category name from an id product in

2019-05-29 07:34发布

I am creating a e-commerce website using woo commerce. I am struggling with a code that how to display the category name of the product using category id in woocommerce?.

In wordpress its easy to display the category name by id as get_the_category_by_id(3). So that it display the name of the id 3.

By the same way how to display the category name by id in woocommerce?

3条回答
老娘就宠你
2楼-- · 2019-05-29 07:44

You can use wp_get_post_terms to get category id of any product like this :

$term_list = wp_get_post_terms($product_id, 'product_cat', array('fields' => 'ids'));

I am just fetching id's of categories assigned to the particular product, You can fetch name also.

Hope this will be useful.

查看更多
SAY GOODBYE
3楼-- · 2019-05-29 07:46

you can use something like this

$product_cats = wp_get_post_terms( your_id, 'product_cat' );

Please, let me know whether it helps.

print_r($product_cats);
查看更多
等我变得足够好
4楼-- · 2019-05-29 07:50

Try this function to get product category name

function get_product_category_by_id( $category_id ) {
    $term = get_term_by( 'id', $category_id, 'product_cat', 'ARRAY_A' );
    return $term['name'];
}
$product_category = get_product_category_by_id( $your_category_id );

Hope this will be useful.

查看更多
登录 后发表回答