我希望显示第二个列出的类别(如果不存在,那么我想显示第一个(主要类别)这是我到目前为止的内容:
<?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;
}
?>
到目前为止将显示第二个,但不会退回到列出的第一个类别。
如果我清楚地理解了您的问题,则可以使用以下代码实现:
<?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
}
?>