I have to get and show only one category name from a product. I have almost read everything and tried everything.
<?php
$term = get_the_terms( $post->ID, 'product_cat' );
foreach ($term as $t) {
$parentId = $t->all;
if($parentId == 0){
echo $t->name;
}else{
$term = get_terms( 'product_cat', array('include' => array($parentId)) );
}
}
?>
It shows one long string with all the category names. How should I get only one category and show its name.
Before I begin, just one note, there is no property called $all
in get_the_terms
. Here are the available fields which you can use
stdClass Object
(
[term_id] =>
[name] =>
[slug] =>
[term_group] =>
[term_order] =>
[term_taxonomy_id] =>
[taxonomy] =>
Get only one product category woocommerce =>
[parent] =>
[count] =>
[object_id] =>
)
I’m not very sure what you want to achieve looking at your code, but if you need only one term from the returned array, you can do something like this: (NOTE: get_the_terms
returns a WP_ERROR
object on invalid taxonomy, so you want to check that, also check whether or not you have terms retrieved)
$terms = get_the_terms( $post->ID, 'product_cat' );
if ( $terms && ! is_wp_error( $terms ) ) {
echo $terms[0]->name;
}
$terms[0]
will return the first term in the returned array.