Get the category name from a WooCommerce product using the product id or the category id

2.2k Views Asked by At

I am trying to get the category name of a product (for example "nutrition", "sport", etc), but I can't.

I'm trying this way:

$test = wc_get_product_category_list(1202);

But what I get is the following:

<a href="https://example.es/product-category/nutricion/sustitutivos/nutricion-batidos/" rel="tag">Batidos</a>, 
<a href="https://example.es/product-category/nutricion/" rel="tag">Nutrición</a>

I just need the tag "Batidos", "Nutrición"...

I would really appreciate any help, I've been trying and reading for a long time but I can't ...

Regards and thanks.

1

There are 1 best solutions below

0
On BEST ANSWER

To get the product category name(s) from a product Id, use instead wp_get_post_terms() function:

$product_id = 1202; // product Id
$term_names_array = wp_get_post_terms( $product_id, 'product_cat', array('fields' => 'names') ); // Array of product category term names
$term_names_string = count($term_names_array) > 0 ? implode(', ', $term_names_array) : ''; // Convert to a coma separated string
echo $term_names_string; // Display the string

To get the product category name from a product category Id, use get_term-by() function as follows:

$term_id   = 125; // Product category term Id
$term      = get_term-by( 'term_id', $category_term_id, 'product_cat' ); // The WP_Term Object
$term_name = $term->name; // Get the term name from the WP_Term Object
echo $term_name; // Display

Tested and works.