【发布时间】:2017-10-30 00:37:26
【问题描述】:
我正在尝试在 Wordpress 网站中显示分配给任何帖子的类别,并使用类别 slug 作为类名称为每个类别设置独特的背景颜色。
我尝试了下面的代码,它显示了任何帖子的类别列表,但复制了列表并将 a slug 类添加到每个列表而不是每个类别。我确定重复是由于两个 foreach 循环造成的,但除非我有另一个,否则我无法无误地工作。
<?php $terms = get_the_terms( $post->ID , 'category');
if($terms) {
foreach( $terms as $term ) {
$categories = get_the_category();
$separator = ' ';
$output = '';
foreach( $categories as $category ) {
$cat_obj = get_term($term->term_id, 'category');
$cat_slug = $cat_obj->slug;
$output .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" class="post-category-' . esc_attr($cat_slug) . '" alt="' . esc_attr( sprintf( __( 'View all posts in %s', 'textdomain' ), $category->name ) ) . '">' . esc_html( $category->name ) . '</a>' . $separator;
}
echo trim( $output, $separator );
}
}
?>
我最终得到的是一个列表,其中第一个类别 slug 作为一个类,然后是一个第二个列表,其中第二个类别 slug 作为一个类:
<a href="http:site.ca/category/archive-posts/" class="post-category-archive-posts" alt="View all posts in Archive Posts">Archive Posts</a>
<a href="http://site.ca/category/making-decisions/" class="post-category-archive-posts" alt="View all posts in Decision Making">Decision Making</a>
<a href="http://site.ca/category/archive-posts/" class="post-category-making-decisions" alt="View all posts in Archive Posts">Archive Posts</a>
<a href="http:site.ca/category/making-decisions/" class="post-category-making-decisions" alt="View all posts in Decision Making">Decision Making</a>
任何有关如何解决重复的帮助将不胜感激。
【问题讨论】: