我试图在wordpress中显示最多2个类别,并设法这样做,只是不知道如何检测第二个。
<?php
while ( have_posts() ) : the_post();
$terms = get_terms( 'directory_categories', 'orderby=name&hide_empty=1&hierarchical=0' );
// I am getting the categories
$i = 0;
$len = count($terms); // counting the categories
foreach($terms as $term) {
// terms is an array of objects (http://codex.wordpress.org/Function_Reference/get_terms)
$i++;
if ($i < 3) {
//if it reached second loop then displays with '/'
$array[] = $term->name;
$limit = count($array);
?>
<a href="<?php echo get_term_link( $term->slug, 'directory_categories' ); ?>"><?php echo $term->name; ?></a>/
<?php
// else if it reached second loop and second loop is 2 then it should omit the slash
} elseif($i < 3 && i == 2) { ?>
<a href="<?php echo get_term_link( $term->slug, 'directory_categories' ); ?>"><?php echo $term->name; ?></a>
<?php } else { } ?>
<?php } ?> <!-- end foreach -->
endwhile;
?>
CURRENT OUTPUT
Category 1 / Category 2/
期望输出没有结束斜杠
Category 1 / Category 2
我很确定逻辑是错误的,请告诉我我错在哪里。
请使用下面的代码(我已经添加了注释,以便您可以轻松维护它):
<?php
while ( have_posts() ) : the_post();
$tax = 'directory_categories'; // your taxonomy
$total = 2; // number of categories to show for each post
$sep = ' / '; // separator you want to use
$terms = get_the_terms(get_the_ID(), $tax);
if ($terms && !is_wp_error($terms)) {
$terms = array_values($terms);
foreach ($terms as $key => $term) {
echo '<a href="' . get_term_link($term->slug, $tax) . '">' . $term->name . '</a>';
if ($key < $total - 1 && count($terms) >= $total) {
echo $sep;
}
if ($key == $total - 1) {
break;
}
}
}
endwhile;
?>