Treehouse: Grow your CSS skills. Land your dream job.

Last updated on:

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;
        }
        $thecount--;
        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.

Comments

  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
        if(!$id){
            $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){
            if(!in_array($cat-&gt;cat_ID,$exclude)){
                $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 :)

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 in triple backtick fences like this:

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