Hide a single category in WordPress

Advertisement:

Recently, I was skimming through the WordPress Plugin Directory. I was looking for a plugin to hide a single category in WordPress, but doesn’t hide its posts. That plugin should only the category from the category listing beneath the (single) post and the sidebar. The reason is: I want to create an additional category that is listed nowhere in the frontend, but is still accessible from the category-archive page. Got that? ;-) No? Here’s a use case:

Every now and then, I am posting images from my flickr-account. I would like to place them in the category flickr. But the category flickr should not be named underneath the post This article was posted in: Photography and flickr., it should only name the category Photography. Furthermore, i do not want the category flickr to be listed in the sidebar. But I want all posts to be listed when accessing the link /category/flickr/.

This is the English translation of the post “Kategorie in WordPress verstecken“, first published in German on my blog r.o.b.’s Kellerclub. To read this German original, follow the beforementioned link to the second page of this article.

Ok, this seems to be a pretty eccentric case, but it is just an example.

So I searched through the plugin directory and found … nothing. I’m not sure if the reason is in the search function itself, the plugin descriptions or my search phrases – I searched for exclude category, category exclusion, category visibility, etc. Eventually, I found nothing that I could use for my case. Most of the plugins I found only had a simple functionality: Choose one or more categories named X or Y and hide them completely. So they were not only hidden in the sidebar, in the feeds and in the posts, but also hid all posts of that category.

I challenged the search engine of my choice and quickly came down to hacking WordPress’ the_category-function. Here, I would want to hook in and hide the corresponding category. I searched further and found a solution on how to exclude a single category from WordPress’ the_category function.

The code to hide a single category in WordPress

I started with removing the category-entry from my single post entries – basically all template files had a code to display the list of categories that this article was published in. I improved the original function with the usage of category IDs. I like using IDs better, because they’re supposed to be unique and static. Even after renaming a category multiple times, the category ID will always remain the same.

You’ll obtain the category ID from WordPress’ backend when hovering over the category entry in Posts → Categories or when copying the link to the category. The link will look something like /wp-admin/edit-tags.php?action=edit&taxonomy=category&tag_ID=4&post_type=post. The number following tag_id= is the category ID you are looking for.

In your functions.php you add the following filter (source code quoted from the origin source and improved by using category IDs):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function the_category_filter($thelist,$separator=' ') {
	if(!defined('WP_ADMIN')) {
		//Category IDs to exclude
		$exclude = array(17);
 
		$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);

In line 4 of this function, you’ll add the category IDs that you want to exclude. To have multiple categories excluded, simply enter them as comma-separated values, e.g. $exclude = array( 7, 17, 25 );. The add_filter-hook finally alters the output of the_category based on the function. With this code, the corresponding categories will not be shown in your single posts and archive pages anymore, or simply said: whererever your template is using the the_category-function.

Hide the category in the category widget

Unfortunately, WordPress’ built in category sidebar-widget will not be affected by the above function to hide a single category in WordPress. You’ll need another one to accomplish that. But altering the category widget is very well documented in the WordPress Codex. I also simply copy and pasted the mentioned code:

25
26
27
28
29
30
31
32
33
34
function widget_categories_args_filter( $cat_args ) {
       $cat_list = array( 17 );
       if ( $cat_args['exclude'] ) {
               //TODO: write code to insert category ids into existing list
       } else {
               $cat_args['exclude'] = implode( ',', $cat_list);
       }
       return $cat_args;
}
add_filter( 'widget_categories_args', 'widget_categories_args_filter', 10, 1 );

The code actually looks incomplete due to the comment in the TRUE-condition in the if-clause, but it is fully functional anyways: it excludes the categories by ID in the sidebar category widget.

Implementation

You will have to add both functions into your theme’s functions.php to make them work. If you are using a standard public WordPress theme, I strongly suggest creating a child theme, since all changes are overwritten when the theme gets an update.

I’m happy to take your hints on improving, simplifying or just shortening the code to hide a single category in WordPress, since I’m not a WordPress pro-developer. I just took the functionality as found – and it works! :-)

Like this post? Share it!
Advertisement:

2 thoughts on “Hide a single category in WordPress

  1. Hallo Rob,

    vielen Dank für deinen Artikel.

    Ich selber bin gerade dabei und möchte eine bestimmte Kategorie von meiner Blog-Übersicht ausschließen und einen “extra Blog” bestehend aus dieser Kategorie erstellen.

    Im Prinzip genau wie du es möchtest, allerdings bin ich gerade etwas überfragt.

    Muss ich die kompletten Zeilen (1-23) aus deiner ersten Beschreibung so in die functions.php einfügen?
    Oder nur die Zeile 4?

    Ich hatte nun Zeile 1-22 eingefügt und die Kategorie ID eingefügt, trotzdem wird der Artikel angezeigt.

    Zeile 23 hatte ich jetzt nicht mit kopiert, da dort ja auch zwei ID’s stehen, ich aber leider nicht weiß, was mit diesen dann passieren wird.

    Vielleicht kannst du mir hier ja weiterhelfen :-)

    Viele Grüße
    Stefan

    • Hallo Stefan,

      ja, du musst Zeile 1 bis einschließlich 23 in die functions.php mit aufnehmen. Zeile 1 bis 22 ist die Funktion, die definiert welche Kategorien (Zeile 4, $exclude) ausgeblendet werden und wie dies geschehen soll.

      Zeile 23 fügt diese Funktion dem Kategorie-Filter hinzu und bestimmt, dass sie immer dann laufen soll, wenn eine Kategorieliste mit der u.g. Funktion abgefragt wird. Wenn du das weg lässt passiert, wie du beobachtest, nichts :-)

      [The the_category filter is] applied to the list of categories (an HTML list with links) created by the get_the_category_list function. Filter function arguments: generated HTML text, list separator being used (empty string means it is a default LI list), parents argument to get_the_category_list.

      Die Beiden Zahlen am Ende des Aufrus bestimmten die Priorität (10) und die Anzahl der Variablen, die dem Filter übergeben werden sollen (2, nämlich $thelist,$separator=' '

      Weitere Infos:
      WP code reference add_filter
      WP Plugin API/Filter Reference

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>