1

I want to include something like the the_category function in a WordPress post, which by default echoes a list of links to all categories the post is attached separated by comma, but I want to exclude some categories from listing in certain views. In some cases I have to exclude all children ones from appearing, in others a top category or random specific categories.

1

Not sure but i think you can try this

function my_category_filter($cats){
   //exclude these from displaying
   $exclude = array("Large Announcement", "Announcement", "News");
   $Catds = array();
   foreach ($cats as$cat){
      if (!in_array($cat,$exclude)){$Catsa[] = $cat;}
   }
   return $Catsa;
}

add_filter('the_category','my_category_filter');
0

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

function the_category_filter($thelist,$separator=' ') {
     // list the IDs of the categories to exclude
     $exclude = array(366);
     // 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);

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(' ').

Credit: http://www.stemlegal.com/greenhouse/2012/excluding-categories-from-the-category-tag-in-wordpres/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.