How to Get a WordPress Category Name Without the Link
If you ever have the need to display the name of your current category without a link, the following code will let you do that.
<?php
foreach((get_the_category()) as $category) {
echo $category->cat_name . ‘ ‘;
}
?>
You will need to insert this in your theme’s files in the appropriate place.
Get WordPress Category Name in Action
Let’s take a look at a few quick examples of how you can use this.
Keeping in mind that this will only display the name of the category, you can use it in conjunction with other text. For example, let’s set it to be part of a sentence on a single post page that says …
This post is from the ______ category.
The blank, of course, will be filled in with the name of the category. In this example, it’s a post in the Music category.
So we can put the following in our single.php file (or wherever is appropriate in your theme).
This post is from the <?php foreach((get_the_category()) as $category) { echo $category->cat_name . ‘ ‘; } ?> category.
I will also put <strong> tags around it to make it bold, so the complete line I am inserting will look like this:
<strong>This post is from the <?php foreach((get_the_category()) as $category) { echo $category->cat_name . ‘ ‘; } ?> category.</strong>
Putting Your Category Title in Your Headline
As another example, let’s say you want to put your category name in your title. Because titles are super important for SEO, perhaps you want to make sure the category is always included.
So, going into your theme files, first you will want to find the code that generates the title. In the theme I’m working with, it looks like this:
<h1 ><?php the_title(); ?> </h1>
And so then I just add my category name code to the end, and I’ll put a divider bar between the two so that it doesn’t look strange. Now my titles will always come out with the following structure: Post Title | Category Name.
Here’s my code now:
<h1 > <?php the_title(); ?> | <?php foreach((get_the_category()) as $category) { echo $category->cat_name . ‘ ‘; } ?> </h1>
And here’s the result.