0

I'm trying to show the category name in my category.php but it's not working when I have posts assigned to multiple categories as it chooses the first category.

<h1><?php $cat = get_the_category(); echo $cat[0]->cat_name; ?></h1>

So I tried by using another method which is to show the category name using the slug URL but that shows nothing.

<h1><?php $cat = get_category_by_slug( $slug );
echo $cat->name; ?></h1>

Output is <h1></h1>

Basically, I want someone opening example.com/category/team to see <h1>Team</h1> or example.com/category/projects to see <h1>Projects</h1> irrespective of the posts being assigned to multiple categories.

What am I doing wrong?

1 Answer 1

1

For the heading on a category archive use either:

the_archive_title();

Or:

single_term_title();

The first one can be used on the template for any archive, while the second should only be used on category, tag, or taxonomy archive templates.

You shouldn’t need to get anything from any of the individual posts. They may have other categories and the category relevant to the current archive might not be the most relevant.

1
  • WOW!! I have been scratching my head over this for the last 2 days! Thank you so much. The single_term_title(); works. Nov 19 at 5:17

Your Answer

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

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