Wordpress

Show Just One Category Name in WordPress Posts Loop

Often we attach a lot of categories while composing a wordpress post, but we want to show just one category name in the post loop, so that user may not get confused and may be able to click on a single category. This is quite easy to be done in the case of WordPress.

If you are not aware of the WordPress posts loop then you should read the following detailed article explaining the basics of a wordpress loop: WordPress Posts Loop Explained in Detail

One Category Name in WordPress on homepage

Show Just One Category Name on Your WordPress Blog Posts:

We need to call the categories of the specific wordpress posts. The categories will be called in an array and then we shall select the first category in the array. Later that selected category from the array will be printed using the php. We can use the word echo also instead of print. Didn’t get ? No problem, just go on with the code part and you will be done.

PHP Code to show just one category in WordPress Post Loop:

Following is the php code to call an array of the categories, and later selecting the first category and echoing it on the page.

<p class="cat-name talkofweb">Filed Under: <?php $category = get_the_category();
if ( $category[0] ) { echo '<a' . ' class="' . $category[0]->cat_name . '"  href="' . get_category_link( $category[0]->term_id ) . '">' . $category[0]->cat_name . '</a></p>'; }?>

Explanation of the “Code For Showing One Category in WordPress”:

The above code calls the categories name assigned to the WordPress post using get_the_category(); and then assigns the array to the $category variable. Later, I selected $category[0] and then echoed the link and category name. And used them accordingly in the <a href=”Category Link”>Category Name</a> tag of html.

The above code must be added in the Loop. And the code is going to output something like this: Filed Under: Category Name.

CSS Code to Design the Category Name:

I have added a class to the above echoed category name, the class is “cat-name” through the cat-name using CSS you can practically design the visual sense to show only one category name. Suppose, you got a black background in your blog and you want to make the color of  Filed Under and Category Name to be white then the code will be like this:

p.cat-name {
/* Styling the filed under text */
color: #fff;
}
.cat-name a {
/* styling the link of the category name */
color: #fff;
}

Thus, using the above code you can do anything to the paragraph text the “Filed Under” plus the link color of the category. I am planning to write another detailed post to let you style the HTML and PHP elements. So, Don’t forget to subscribe to the tutorials category below.

See Also: Creating Navigation bar Using CSS and HTML