我正在使用以下代码(特别是以<p class="category">
开头的行)打印自定义公文包归档中每个帖子的相应类别。
我该如何修改代码,以便在最后一个代码中,除了逗号外,还使用了"与"符号?通过这种方式,我可以让它打印"身份,打印,和网页设计",而不是"身份,打印机,网页设计"
代码:
<?php if ( have_posts() ) : $count = 0;
while ( have_posts() ) : the_post(); $count++;
$classes = 'portfolio-item item-' . $count;
if ( $count % 3 == 0 ) {
$classes .= ' ie-col3';
}
if ( !has_post_thumbnail() || post_password_required() ) {
$classes .= ' no-thumb';
} ?>
<div class="<?php echo $classes; ?>">
<?php if ( has_post_thumbnail() && !post_password_required() ) { ?>
<a href="<?php the_permalink() ?>" rel="bookmark" class="thumb"><?php the_post_thumbnail( $thumbnail ); ?></a>
<?php } ?>
<a href="<?php the_permalink() ?>" rel="bookmark" class="title-overlay"><?php the_title() ?></a>
<p class="category"><?php echo strip_tags(get_the_term_list( $post->ID, 'portfolio_category', '' , ', ')); ?> Design</p>
</div>
<?php endwhile; ?>
<?php portfoliopress_content_nav(); ?>
<?php else: ?>
<h2 class="title"><?php _e( 'Sorry, no posts matched your criteria.', 'portfoliopress' ) ?></h2>
<?php endif; ?>
我使用此函数以类似的方式显示类别。诀窍是创建一个空数组,并将您的类别添加到该数组中。
要插入逗号,请使用implode(', ', $array)
创建:红色、蓝色、绿色
如果要添加"与"符号,可以使用array_pop($array)
,它将删除最后一个元素。只需检查数组的长度是否至少为3。
// Display categories tagged by the post.
if (get_the_category()) {
// Add our categories to a new array
$category_list = array();
// Sift through every category, optionally doing some maintenence.
foreach(get_the_category() as $cat) {
if ( $cat->name == 'uncategorized' ) continue; // Skip uncategorized category
// Create an <a> element for our category
$category_list[] = sprintf( '<a href="%s" title="View all posts in %s">%s</a>',
esc_attr( get_category_link( $cat->term_id ) ),
esc_attr( $cat->name ),
$cat->name
);
}
// If we have multiple categories, display a list
if (count($category_list) > 2) {
// Take the last category off, then add it on after an ampersand.
$last_category = array_pop($category_list);
echo sprintf( 'Categories: %s & %s'
implode(', ', $category_list),
$last_category
);
} else {
if (count($category_list) > 1)
echo 'Categories: ', implode(', ', $category_list);
elseif (count($category_list) == 1)
echo 'Category: ', $category_list[0];
}
}
浏览两次帖子列表。第一次只是得到一个总数,没有处理数据。第二次,看计数。当你到达最后一个项目的下一个时,不要使用","使用"&"。