Display category name of custom posts only once in the loop

I have a custom post type called Projects and for it some categories.

I would like to display the category name of the posts in the loop but only once.

I am using this but the category is being displayed on top of every post.

For example if the 2 posts are in the same cetegory, now I see the category name twice in the same loop.

How can I solve it?

My code:

?php
  $category = the_category();
?
h2 style=text-transform: uppercase;
?php
  if($i == 1) { 
    echo $category[1]-cat_name; 
  }
  $i++;
?
/h2     

Many thanks in advance

Topic loop custom-post-types Wordpress

Category Web


Display category name of custom posts only once in the loop

Which page template do you want to display the category name? category page or single page, I am pretty sure this code will work.

<?php
    $category = get_the_category();
?>
<h2 style="text-transform: uppercase;">
<?php
    foreach ( $category as $key=> $val ){
        echo $val->cat_name .'<br>';
    }
?>
</h2>

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.