Brain Food for Web Developers

Categories "Featured" and "Services" have been separately highlighted in blue.

Highlight Post Categories in WordPress using the_category()

Categories "Featured" and "Services" have been separately highlighted in blue.Here’s a quick code snippet that allows you to style the post categories displayed alongside each WordPress post.

Basically, during ‘the loop’ you’d use the_category() function to output the categories that the current post belongs to. Here is a simple example of the_category function in use:

<p>Posted in <?php the_category(', '); ?></p>

Example output: Posted in Featured, Services

The first parameter in the_category() function is the separator. In the above example I’ve used a comma to separate the categories listed but it’s also common to add arrows, blank spaces, or bullet points.

What I want to accomplish is to highlight each category by wrapping them in a span tag. The problem is that the separator is only placed between categories so in order to wrap each one I need to place an open span before and after I call the_category function. Then I can place a closing and opening span as the separator. Like so:

<p>Posted in <span class="round label"><?php the_category('</span> <span class="round label">'); ?></span></p>

Which will output the following code for two categories:

<p>Posted in
<span class="round label> <!-- First category link code --> </span>
<span class="round label> <!-- Second category link code --> </span>

Read more about the_category function and it’s parameters from the WordPress codex.

Author: Graham

My name is Graham and I'm a Scottish web developer living in California. I love working with clean code to make attractive and usable websites. I'm also interested in cooking, gardening, and taekwondo.

Comments are closed.