. : April 21, 2015 : .

How to display the categories of a post in WordPress

Let’s say you write about a variety of topics. Wouldn’t it be a good idea to organize your content by topic?

For example, you might have a cooking blog. Your site’s visitors might expect to see your content organized in categories like so:

  • Salads
  • Soups
  • Pastas
  • Appetizers
  • Desserts

This would make it easier for your site’s visitors to find the things that they are interested in. Making a site easy to navigate makes its visitors happy and keeps them coming back.

Before we go any further, you should know that organizing your site by categories can effect your search engine optimization (SEO). I will not be covering that here. I’m not an expert in that area, but you should be able to find plenty of people who are by searching for them. This scope of this post is focused only on displaying and linking to the categories of a post.

OK, let’s get started!

The first thing I like to do is think of the markup. For something like this, I like to use unorganized lists. Like this:

<ul>
 <li>Salads</li>
 <li>Soups</li>
 <li>Pastas</li>
 <li>Appetizers</li>
 <li>Desserts</li>
</ul>

So, let’s create an unorganized list that will be populated by a PHP loop that retrieves all the categories that a post is associated with. The end result might look something like this:

<ul class="blog-categories">
	<?php
		//get all the categories the post belongs to
		$categories = wp_get_post_categories( get_the_ID() );
		//loop through them
		foreach($categories as $c){
			$cat = get_category( $c );
			//get the name of the category
			$cat_id = get_cat_ID( $cat->name );
			//make a list item containing a link to the category
			echo '<li><a href="'.get_category_link($cat_id).'">'.$cat->name.'</a></li>';
		}
	?>
</ul>

You might also want to have a menu on your site that displays all categories. That way, your site visitors can get right down to business. WordPress provides a function called “wp_list_categories” that will do this for us without having to write much code at all. The only thing I don’t like about it is that by default it generates an unordered list within a list item tag. There is a way to prevent that, though:

$args = array(
	//set title_li to '' prevent it from wrapping the <ul> in an <li>
	'title_li' => __( '' )
);
wp_list_categories( $args );

Conclusion

So, there you have it. Now your site’s visitors can browse by category!

References:

Categories:

Leave a Reply