WordPress Wednesday: Excluding Categories from the_category();

In this week’s WordPress Wednesday, we’re covering a simple way to exclude categories from the_category() tag’s output in your themes.

On a recent project, I not only wanted to make sure the ‘Uncategorized’ tag didn’t display; I also needed to hide two additional tags that were doing some heavy-lifting in the background, but didn’t need to be displayed on the site. Unfortunately, the_category() tag doesn’t have an option to exclude specific categories.

Enter this handy function from the WordPress support forums — just add it to your theme’s functions.php file:

[php] function the_category_filter($thelist,$separator=' ') { // list the IDs of the categories to exclude $exclude = array(4,5); // create an empty array $exclude2 = array(); // loop through the excluded IDs and get their actual names foreach($exclude as $c) { // store the names in the second array $exclude2[] = get_cat_name($c); } // get the list of categories for the current post $cats = explode($separator,$thelist); // create another empty array $newlist = array(); foreach($cats as $cat) { // remove the tags from each category $catname = trim(strip_tags($cat)); // check against the excluded categories if(!in_array($catname,$exclude2)) // if not in that list, add to the new array $newlist[] = $cat; } // return the new, shortened list return implode($separator,$newlist); } // add the filter to 'the_category' tag add_filter('the_category','the_category_filter', 10, 2); [/php]

Initially, I did have some issues with this function; after some tinkering around, I realized I needed a separator declared in the_category() tag, like a comma, dash, etc. In this case, I was using just a space — the_category(' ') — which wasn’t working, but swapping it out for a non-breaking space did the trick: the_category(' ').

Have you run across any WordPress tags are missing options you need?

  1. Marc said:


    ich hab das Ganze jetzt einfach so in meine functions.php ans Ende kopiert. Muss ich jetzt nur noch in Zeile 3 die Kategorie IDs anpassen?

    (vielleicht eine dumme Frage, aber ich hab keine Ahnung von php/Wprdpress und Co….)

    Danke 🙂

    @ 3:01 am
  2. Marc – Sie sind richtig! 🙂

    @ 8:36 am
  3. Ian Douglas said:

    This works well, but it also hide the categories in the backend, where you chose which category a post is filed under. Is there a way to tweak this so the category entry shows in the backend, but is hidden on the frontend?

    @ 3:09 pm
  4. Ian Douglas said:
    @ 3:10 pm

Leave a Comment

Note: Fields marked with a * are required; email addresses are not published.

Legal FAQ Collections