在 Woocommerce 中显示第二类(不是主要)如果没有第二类,则显示主要
In Woo comerce show second category ( not primary ) if there is no second category, then show primary
我希望显示第二个列出的类别(如果存在),如果不存在,那么我想显示第一个(主要类别)
这是我目前所拥有的:
<?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
}
?>
我希望显示第二个列出的类别(如果存在),如果不存在,那么我想显示第一个(主要类别) 这是我目前所拥有的:
<?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
}
?>