首页 文章

Wordpress主题:仅显示一个类别

提问于
浏览
1

我的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;

This is the form that can be seen

1 回答

  • 1

    以下代码可以帮助您 . 您不需要foreach循环,因为您只希望打印第一类 . 希望能帮助到你 .

    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">';
                  $color_code = get_theme_mod( 'metro_magazine_category_color_' . $categories_list[0]->term_id );
                      if ( $color_code ) {
                         $output .= '<a class="category" href="' . esc_url( get_category_link( $category[0]->term_id ) ) . '" style="background:' . esc_attr( $color_code ) . '" rel="category tag">'. esc_html( $categories_list[0]->cat_name ) .'</a>';
                      }else{
                         $output .= '<a class="category" href="' . esc_url( get_category_link( $categories_list[0]->term_id ) ) . '"  rel="category tag">' . esc_html( $categories_list[0]->cat_name ) . '</a>';
                      }
              $output .= '</div>';
              echo $output;         
          }
      }
    
    }
    

相关问题