Tim TrottTim Trott.ninja { color:black; visibility:hidden; }

Useful WordPress Category Functions

By , Saturday 24th January 2009 in WordPress

This is a collection of extremely useful functions for working with Wordpress categories. Get parent category, and detect if current category is a sub category or child category of the specified.

These are functions that I found on the web years ago and have been using ever since. They appear on all my WordPress websites.

Firstly we have a function to get the ID of the parent category of the current category.

function get_parent_category() 
{
  foreach ((get_the_category()) as $cat) 
  {
    if ($cat->category_parent) 
      return $cat->category_parent;
    else 
      return $cat->cat_ID;
  }
}

Next we have two functions which form one of the most useful functions ever. It will allow you to pass in a category id and it will tell you if the current post or category is contained within that category, either directly or through child/sub categories.

function in_category_or_subcategory_of($cat_id=0) 
{
  $cats = get_the_category();
  if (!count($cats))
    return false;
  foreach ((array)$cats as $cat) 
  {
    if ($cat->cat_ID == $cat_id) 
      return true;
    if (in_category_dig_parents($cat->category_parent, $cat_id))   
      return true;
  }
  return false;
}
 
function in_category_dig_parents($cat_id, $look_for) 
{
  if ( !$cat_id ) 
    return false;
  if ( $cat_id == $look_for ) 
    return true;
  $cat = get_category($cat_id);
  return in_category_dig_parents($cat->category_parent, $look_for); 
}

To use it, simply call 'in_category_or_subcategory_of' specifying a category id and it will return true or false depending on the category hierarchy.

These functions were not written by myself, and I do not know who did write them. If you know the author, please let me know so I can give credit where credit is due.

My website and its content are free to use without the clutter of adverts, tracking cookies, marketing messages or anything else like that. If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

About the Author

Tim Trott

Tim is a professional software engineer, designer, photographer and astronomer from the United Kingdom. You can follow him on Twitter to get the latest updates.

Further Reading
Leave a Reply

Your email address will not be published.