the_category with Excludes

The WordPress function the_category doesn't offer an exclude parameter. This does:

function exclude_post_categories($excl='', $spacer=' ') {
  $categories = get_the_category($post->ID);
  if (!empty($categories)) {
    $exclude = $excl;
    $exclude = explode(",", $exclude);
    $thecount = count(get_the_category()) - count($exclude);
    foreach ($categories as $cat) {
      $html = '';
      if (!in_array($cat->cat_ID, $exclude)) {
        $html .= '<a href="' . get_category_link($cat->cat_ID) . '" ';
        $html .= 'title="' . $cat->cat_name . '">' . $cat->cat_name . '</a>';
        if ($thecount > 1) {
          $html .= $spacer;
        echo $html;

Plus as long as you have that, you can alter the output however you want which is nice.

Usage is like:

<?php exclude_post_categories("4"); ?>

Which would list all categories excluding the one with the ID of 4.


  1. Ed
    Permalink to comment#

    Ey Up!

    I use a very similar function.

    Goes a little something like this…

    function post_categories($spacer=" ",$exclude="",$id=false){
        //allow for specifiying id in case we
        //want to use the function to bring in 
        //another pages categories
            $id = get_the_ID();
        //get the categories
        $categories = get_the_category($id);
        //split the exclude string into an array
        $exclude = explode(",",$exclude);
        //define array for storing results
        $result = array();
        //loop the cats
        foreach($categories as $cat){
                $result[] = "<a>term_id)."' title='".$cat-&gt;name."'&gt;".$cat-&gt;name."</a>";
        //add the spacer
        $result = implode($spacer,$result);
        //print out the result
        echo $result;

    The replacing > and < and the quotes have messed up the function slightly but you get the idea.
    I think it uses slightly simpler way of adding the spacers and also allowed specifying an id of another post.

    Maybe it will be of use…

    Maybe not :)

  2. DJ
    Permalink to comment#

    There is a problem with this script. Let’s say I have 100 categories on the site… and I exclude 50 categories using the function above. What happens if there are only 5 categories in a post?

    Well, the count would be 5-50 = -45. This messes up the “spacer”.

  3. Alex
    Permalink to comment#


Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences like this:

  function example() {
    element.innerHTML = "<div>code</div>";

We have a pretty good* newsletter.