我正在尝试显示分配给Wordpress网站中任何帖子的类别,并使用类别slug作为类名称为每个类别设置独特的背景颜色。
我已经尝试了下面的代码,它显示了任何帖子的类别列表,但重复了列表,并将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>
任何有关如何解决重复项的帮助都将不胜感激。
答案 0 :(得分:0)
如果您要使用其他功能循环浏览可用类别,则无需查看类别条款。对于get_the_category()
的返回对象,也存在Slug对象属性
<?php $categories = get_the_category();
if(!empty( $categories)) {
$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($category->slug) . '" alt="' . esc_attr( sprintf( __( 'View all posts in %s', 'textdomain' ), $category->name ) ) . '">' . esc_html( $category->name ) . '</a>' . $separator;
}
echo trim( $output, $separator );
}
?>
答案 1 :(得分:0)
get_the_category()
已提供您需要的所有信息。不需要所有额外的循环或数据库查询:
<?php
$the_cats = get_the_category();
if( $the_cats ) ){
$links = array();
foreach( $the_cats as $the_cat ) {
$links[] = '<a href="' . esc_url( get_category_link( $the_cat->term_id ) ) . '" class="post-category-' . esc_attr( $the_cat->slug ) . '" alt="' . esc_attr( sprintf( __( 'View all posts in %s', 'textdomain' ), $the_cat->name ) ) . '">' . esc_html( $the_cat->name ) . '</a>';
}
echo implode( ' ', $links );
}
?>