我的WordPress主题,显示帖子在主页上的所有类别,我只想显示一个类别,即使帖子在多个类别下 .
这是我主题中的代码:
function metro_magazine_colored_category(){
$output = '';
// Hide category for pages.
if ( 'post' === get_post_type() ) {
$categories_list = get_the_category();
if ( $categories_list ) {
$output .= '<div class="category-holder">';
foreach( $categories_list as $category ){
$color_code = get_theme_mod( 'metro_magazine_category_color_' . $category->term_id );
if ( $color_code ) {
$output .= '<a class="category" href="' . esc_url( get_category_link( $category->term_id ) ) . '" style="background:' . esc_attr( $color_code ) . '" rel="category tag">'. esc_html( $category->cat_name ) .'</a>';
}else{
$output .= '<a class="category" href="' . esc_url( get_category_link( $category->term_id ) ) . '" rel="category tag">' . esc_html( $category->cat_name ) . '</a>';
}
}
$output .= '</div>';
echo $output;
}
}e
}
endif;
1 回答
以下代码可以帮助您 . 您不需要foreach循环,因为您只希望打印第一类 . 希望能帮助到你 .