Php 对于一个商业产品,只能获取一个产品类别术语

Php 对于一个商业产品,只能获取一个产品类别术语,php,wordpress,woocommerce,product,taxonomy-terms,Php,Wordpress,Woocommerce,Product,Taxonomy Terms,我有一个关于WooCommerce分类的谜团。 对于不同的产品,我有多个类别。 例如,产品Nike Air Red 我将此产品与两个类别品牌->耐克和鞋->红色 品牌和鞋子是主要类别,耐克和红色是子类别 在产品页面上,我有以下代码 $terms = wp_get_post_terms( $post->ID, 'product_cat' ); foreach ($terms as $term) { echo $term->name; } 输出为NikeRed 有没有办法得到一

我有一个关于WooCommerce分类的谜团。 对于不同的产品,我有多个类别。 例如,产品Nike Air Red 我将此产品与两个类别品牌->耐克鞋->红色 品牌和鞋子是主要类别,耐克和红色是子类别

在产品页面上,我有以下代码

$terms = wp_get_post_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
    echo $term->name;
}
输出为NikeRed

有没有办法得到一个类别? 耐克还是红色

我也试过了

get_ancestors(get_queried_object_id(), 'product_cat')
但此数组为空

请尝试使用
reset()
获取第一个术语,如下所示:

$term_names = wp_get_post_terms( $post->ID, 'product_cat' array('fields' => 'names') );
echo reset($term_names);
这将显示第一个术语名称

使用
end()
将显示最后一个:

$term_names = wp_get_post_terms( $post->ID, 'product_cat' array('fields' => 'names') );
echo end($term_names);

@LoicTheAztec我尝试了
$terms=wp\u get\u post\u terms($post->ID,'product\u cat',数组('parent'=>'0')但这会返回Nike和Red两个类别。我只想要一个