0

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

1
  • If you initially set $i to 1 before The Loop and change the_category() to get_the_category() (the_category() prints category names - get_the_category() retrieves an array of category objects as your code expects). Also note that in PHP array indexes start at 0 - the first category object would be in $category[0], not $category[1].
    – bosco
    Commented May 30, 2022 at 16:53

1 Answer 1

0

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.