I design and develop experiences that make people's live simple

How to Conditionally Display WordPress Post Categories on Screen

Not always, but sometimes when you’re using WordPress for blogging, publishing articles, or other types of content-driven purposes it’s nice to render a post’s category — or categories — on the screen. Inherently, displaying a post’s category is good for visual organization purposes, SEO, and helping your website visitors know there might be more similar articles to interest them. It’s also an opportunity for you to add an internal link to the page and keep your website’s traffic flowing.

Regardless of the how many you’ve assigned to a WP post here’s a solution of how you can conditionally display the post categories from inside The Loop.

Example Code

<div class="article__categories">
  <?php
  $categories = get_the_category();
  $cat_count = count($categories);
  $cat_title = $cat_count > 1 ? 'Categories' : 'Category';
  ?>
  <?php if (!empty($categories)) : ?>
    <span class="article__categories-title"><?php echo __($cat_title); ?>:</span>
    <?php for ($i=0;$i<$cat_count;$i++) : ?>
      <span class="article__categories-item">
      <?php
        echo sprintf(__('<a href="%s">' . $categories[$i]->name . '</a>'), (get_category_link($categories[$i]->cat_ID)));
        if ($cat_count > 1 && $i < $cat_count - 1) {
          echo ', ';
        }
      ?>
      </span>
    <?php endfor; ?>
  <?php endif; ?>
</div>

Explanation

Here’s an explanation of the PHP + HTML code above.

  • Get any categories assigned to the post.
  • Count how many categories there are (or aren’t).
  • Depending on the count, set a singular or plural title text.
  • Render the categories on screen with the appropriate title – if there are any.

So, if your post has categories they’ll get shown on screen. And, if your post doesn’t have categories assigned then they won’t get displayed on screen. Additionally depending on if there is one category or many categories, the code will change the title from the singular-version – Category – to a plural version of Categories.

Pretty cool, right?

On Your WordPress Site

You can use this example on your own WordPress site. Start by pasting it into the desired template file within your site’s active theme. If you’d like, further customize the markup until it fit your needs.

Make sure you’re adding it inside The Loop. Otherwise, you’ll need to include a post id when initially getting the categories.