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

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
    ``` 
    <div>
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
    </div>
    ```
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

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