在Woo节目中显示第二个类别(不是主要类别),如果没有第二个类别,则显示主要类别

问题描述 投票:2回答:1

我希望显示第二个列出的类别(如果不存在,那么我想显示第一个(主要类别)这是我到目前为止的内容:

    <?php $categories = get_the_category();
 if ( ! empty( $categories ) ) {
    echo esc_html( $categories[1]->name );   
} 
else $terms =  get_the_terms( $post->ID, 'product_cat' );
if ( $terms && ! is_wp_error( $terms ) ) {
    echo $terms[1]->name;  

}
  if ( ! empty( $terms[1]->name ) ) {  
       echo $terms[0]->name; 
   }
                            ?> 

到目前为止将显示第二个,但不会退回到列出的第一个类别。

wordpress if-statement woocommerce categories
1个回答
2
投票

如果我清楚地理解了您的问题,则可以使用以下代码实现:

<?php 
$terms =  get_the_terms( $post->ID, 'product_cat' );
if ($terms && !is_wp_error($terms)) {
    if (!empty($terms[0]->name))
        echo $terms[0]->name; // second category
    else 
        echo $terms[1]->name; // first (primary) category 
}
?>
© www.soinside.com 2019 - 2024. All rights reserved.