Web Design that taps into the haromny and vision of your dreams.

Useful Wordpress Category Functions

By on in Coding

258 words, estimated reading time 2 minutes.

This is a collection of extremely useful functions for working with Wordpress categories. Get parent category, and detect if current category is a subcategory 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.

Last updated on: Thursday 22nd June 2017

 

Comments

Have a question or suggestion? Please leave a comment to start the discussion.

 

Leave a Reply

Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

Your email address will not be published.