WordPress Category Slug and How to Show it

Claudia Loens of Wordflirt.com and I recently launched a client site (innermightsports.com).

On all pages, except the home page, I wanted to show the category for the post, or the page title, as well as an image custom to that category/page title. So I needed to get the WordPress category slug, and also the WordPress page slug.

Here’s how I did it.

wordpress category slug thedavebraun

PHP Code to get the WordPress Category Slug

Explanation of the WordPress Category Slug code

There are three major sections that do the bulk of the work. We’ll look at each individually.

1. Grab the slug from the post or page

I simply do a quick query on the current post (remember, in WordPress, a page is simply a certain type of post, so this works for both pages and posts). This provides an array that has all of the information about the current post.

2. Get the category we want to use

I grab the category array from the post. Normally I’d just want to display the first category, but the way we have the categories organized is there are certain sports we have lumped together in an “Other Sports” category, so if that is the case, then we have to check for that.

Sometimes the Other Sports category will appear as the first category in the array, other times the second, so I have to account for that with the comparison.

Last, I make sure to format the category name properly by removing any dashes and capitalizing the first letter of each word.

3. Create embedded CSS

In the last section, I create some embedded CSS (which maybe shouldn’t strictly be done), targeting the required module in our Builder theme. As I build the string, note that if you use this code, you’ll definitely need to make several adjustments here.

Then a comparison is done to the slug string to see which image should be used, and that is inserted into the string.

Finally, the CSS is filled out with the required ending characters, and the slug is returned so that it can be placed into the widget area.

Final words

I placed this code in my functions.php for the theme I’m using.

Even if you don’t want to use a different picture for each page, you can still display the category in the place you want it.