Home > front end >  How to show two genres or categories
How to show two genres or categories

Time:02-03

I am using this function, but it only shows one category.

// SingleGenre
function SingleGenre() {
    global $post;
    $category = get_the_category();
    if (!empty($category[0]))
    if ( $category[0] ) { 
    echo '<span itemprop="genre"><a href="' . get_category_link( $category[0]->term_id ) . '">' . $category[0]->cat_name . '</a></span>';
       }
    }

I would like to show 2 categories using the same function.

Try using the foreach.

CodePudding user response:

Try the following.

// SingleGenre
function SingleGenre() {
    global $post;
    $categories = get_the_category();
    $count = 0;
    foreach($categories as $category) {
        if ($count < 2) {
            echo '<span itemprop="genre"><a href="' . get_category_link( $category->term_id ) . '">' . $category->cat_name . '</a></span>';
            $count  ;
        }
    }
}
  • Related