Excluding categories in the_category

This morning I needed to use the the_category tag but I needed to exclude a tag via a category name.

<?php
	//exclude these from displaying
	$exclude = array("Hood Newz");

	//set up an empty categorystring
	$catagorystrings = array();

	//loop through the categories for this post
	foreach((get_the_category()) as $category)
	{
		//if not in the exclude array
		if (!in_array($category->cat_name, $exclude))
		{
			$catagorystrings[] = '<a href="'.get_bloginfo(url).get_option('category_base').'/'.$category->slug.'">'.$category->name.'</a>';
		}
	}
	echo join(', ',$catagorystrings);
?>

If you’re looking to exclude the category across the entire theme through a filter, you can add this to your funtion.php file.

function the_category_filter($thelist,$separator=' ') {
	if(!defined('WP_ADMIN')) {
		//list the category names to exclude
		$exclude = array('Something','Something Else','Blah','YAY');
		$cats = explode($separator,$thelist);
		$newlist = array();
		foreach($cats as $cat) {
			$catname = trim(strip_tags($cat));
			if(!in_array($catname,$exclude))
				$newlist[] = $cat;
		}
		return implode($separator,$newlist);
	} else
		return $thelist;
}
add_filter('the_category','the_category_filter',10,2);

Thanks to the WordPress Forums.

About the Author, Dan Cameron:

I'm the owner and solution engineer at Sprout Venture, a web solutions company that specializes in web development including WordPress.

I started my first blog in 2003 and transitioned to WordPress in 2004. Since moving to WordPress I've written a few plugins and themes for public consumption. Lately I'm busy engineering/building/coding and have only been able to share a few code snippets.

If you're in need of some web development, web design or custom WordPress plugins and/or themes contact me, I'll be happy to discuss it with you.

Read More »

blog comments powered by Disqus