How to exclude specific categories from the_category()

code How to exclude specific categories from the category()The templates tag, the_category(), is very handy to output all categories to which a post belongs. However, sometimes, we don’t want to show the all cateogries when we use some categories for admin purposes. For example, the popular plugin, Featured Content Gallery requires you to specify a category for the featured content and you don’t want to show the featured content category in the list, and so on.

1. Paste this code in your theme’s function.php, and change ‘FirstCat’ and ‘SecondCat’ to category names that you want to exclude from the list.

<?php
function incomplete_cat_list($separator) {
	$first_time = 1;
  	foreach((get_the_category()) as $category) {
    	if ($category->cat_name != 'FirstCat' && $category->cat_name != 'SecondCat') {
      		if ($first_time == 1) {
        		echo '<a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>'  . $category->name.'</a>';
        		$first_time = 0;
      		} else {
        		echo $separator . '<a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a>';
      		}
    	}
  	}
}
?>

2. To use this function, istead of using the_category(); paste this code in your index.php or single.php

<?php incomplete_cat_list(', '); ?>

Thanks to Technokinetics for this great piece of code.

Author: Takashi Irie

Takashi Irie is an experienced commercial web designer and Wordpress expert based in London. He is very passionate about web design, typography, grid systems as well as Wordpress.

Enjoyed this post? Share it!

  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • StumbleUpon
  • Twitter
  • email
  • RSS

Leave a Comment