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;
        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 :)

Leave a Comment

Posting Code

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like this:

<div>Example code</div>

You don't need to escape code in backticks, Markdown does that for you. If anything screws up, contact us and we can fix it up for you.

*May or may not contain any actual "CSS" or "Tricks".