Excluding categories from the_category()

the_category() is the WordPress template tag which shows the category your post is in. If the post is in multiple categories, it will output them all, linked to the respective archive page.

By default, the_category() creates an unordered list (i.e. a vertical list with bullet points); this looks a bit odd with most themes, so you might want to change it to an inline list separated with spaces, commas or bullets:


<?php the_category(' '); ?>
<?php the_category(', '); ?>
<?php the_category(' &bull; '); ?>

You may also want to exclude a category or two from the list, if there are categories you're using for housekeeping and structure rather than just for classification. Unfortunately, the_category() doesn't have an exclude attribute, so we need to be a little bit more complicated to do that. In the code below, edit the list of categories you want to exclude, and how you want each item in the list separated:

<?php
//edit below for categories you want excluded
$exclude = array("Featured", "Uncategorized");
//how do you want the list separated? just a space is okay
$separator = " | ";
//don't edit below here!
$new_the_category = '';
foreach((get_the_category()) as $category) {
if (!in_array($category->cat_name, $exclude)) {
$new_the_category .= '<a href="'.get_bloginfo(url).'/'.get_option('category_base').'/'.$category->slug.'">'.$category->name.'</a>'.$separator;
}
}
echo substr($new_the_category, 0, strrpos($new_the_category, $separator));
?>

catbaseBy default, WP renders category permalinks as http://domain/category/category-slug. Settings > Permalinks gives you the option to change this. However, if you're using the default, you'll need to explicitly state "category" in Permalinks' settings for the above code to work.

Share this post:
  • email
  • del.icio.us
  • Facebook
  • FriendFeed
  • LinkedIn
  • StumbleUpon
  • Tumblr
  • Twitter

Tags:

Posted by Sue on September 5, 2009 in WordPress.

2 comments to "Excluding categories from the_category()"

  1. Valex wrote:

    Could you please suggest how to make it work if we don't have the "category" in Permalink!

  2. Mark wrote:

    My link is in my email address thanks nut it's a new theme i'm working on that is my issue here.

    I'm wondering where abouts I put the code you supplied us above.. in theme fucntions is it?

    Thanks

Leave a Reply