Share and Enjoy

How to remove categories from the_category function in WordPress

You might needed this hack if you want to use a single installation of WordPress for multiple sections. the_category() is WordPress Template Tag that displays a link to the category or categories a post belongs to. If you want to eliminate a specific category from the string returned by the_category, you can use the add_filter() to achieve that.

For Instance you don’t want to show the category Uncategorized and Private, in order to do so first put the paste code at the end of your functions.php located in your current theme folder.

function the_category_filter($thelist,$separator=' ') {
	if(!defined('WP_ADMIN')) {
		//Category Names to exclude
		$exclude = array('Uncategorized', 'Private');
		
		$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);

The above code will exclude the categories you added in $exclude on line 4. Now if you want to eliminate the categories on base of Category ID instead of Category Name (which, in my opinion is a better approach), you’ll need the following code.

function the_category_filter($thelist,$separator=' ') {
	if(!defined('WP_ADMIN')) {
		//Category IDs to exclude
		$exclude = array(1,5);
		
		$exclude2 = array();
		foreach($exclude as $c) {
			$exclude2[] = get_cat_name($c);
		}
		
		$cats = explode($separator,$thelist);
		$newlist = array();
		foreach($cats as $cat) {
			$catname = trim(strip_tags($cat));
			if(!in_array($catname,$exclude2))
				$newlist[] = $cat;
		}
		return implode($separator,$newlist);
	} else {
		return $thelist;
	}
}
add_filter('the_category','the_category_filter', 10, 2);

On line 4, you can put the Category IDs you wants to eliminate.
Happy Blogging!

Enjoyed this Post?

Share and Enjoy

Facebook Feeds