/ coding

Putting WordPress categories into individual divs

I’m on the last train from Kyoto to Osaka. It is a slow train full of drunk people half-sleeping, listening to smartphone lullabies in their earbuds. The train hums and rocks gently. I’ve had some beers myself, but I’m not sleepy. So I’ll just walk through a thought process. It may be incredibly rudimentary. It could be mistaken.

One of the more puzzling things I’ve come across in my early experience of writing a theme for WordPress has had to do with putting WordPress categories into pills.

In other words, putting each category for a post into its own div tag was so unexpectedly simple that it took me a while to figure it out.

Since each post has anywhere from 1 to an infinite number of categories, I expected I was going to have to write a loop that assigned each category to a div with a CSS class and printed it until there were none left to print.That didn’t work out at all. I don’t remember all of the various errant results I produced, but the most amusing was an infinite loop of the post categories, styled as expected, but repeated to eternity.

After that attempt, I had an inkling that maybe the_category() was its own loop of sorts. If so, why not just wrap the_category() in div tags?

So here is what I tried next (the class in question is called “catpill”):```


Here is the result:
Individual divs for WordPress categories - Ash Ryan Beats

This is clearly wrong, but it is getting somewhere. It’s styling the categories correctly for the most part, but in bulk and in a list.

Based on the previous attempts, it was clear that the_category() was looping but that wrapping it in div tags wouldn’t be sufficient; something needed to interrupt the_category() each time a category was printed to close the div. I had a look at the WordPress Codex and noticed that one type of argument accepted by the_category() was $separator, which could be a string.

So I tried entering HTML/CSS as that string:

<div class=“catpill”><?php the_category(‘</div><div class=“catpill”>’) ?></div>

And it worked just fine:
Individual divs for WordPress categories 2 - Ash Ryan Beats

Here is the HTML generated by the above line of code, which is as expected:
Individual divs for WordPress categories 3 - Ash Ryan Beats

What’s happening in the line of code above is that the $separator is both an end of one div and the start of another. Finally, the_category() is capped by a closing div tag when the_category() is done working.I wonder if this solution is a best practice, but by all measures that I am aware of it is solid: one line of code (instead of several) that results in clean HTML.

Putting WordPress categories into individual divs
Share this