WordPress provides a template tag that outputs all of the categories to which a post belongs: the_category(). You might use this to create a complete, comma separated list of a post’s categories using something like this: <p class="postCategories">Categories: <?php the_category(', '); ?></p>.
Sometimes, though, you don’t want a complete category list, because some of your categories are for administrative use only. Unfortunately, there’s no easy way to generate an incomplete category list. You can’t just pass a variable to this function excluding a category; the_category('exclude=1') doesn’t work.
So if we want an incomplete category list then we need to create our own custom function. Adding the following code (adapted from code suggested by MichaelH on the WordPress forums) to your functions.php theme file will create a function that generates a comma separated list of a post’s categories excluding “FirstCat” and “SecondCat”:
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>’;
}
}
}
}
To use this function, just add something like this to your index.php or single.php theme files: <p class="postCategories">Categories: <?php incomplete_cat_list(', '); ?></p>.
Replace “FirstCat” (”SecondCat”, etc.) with the names of the categories that you want to exclude. If you want something other than a comma between categories, then change the value of $separator passed when you call the function.
July 2nd, 2009 at 11:00 am
Great post!! Thanks a lot! Works out for me.