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

Useful Wordpress Category Functions

Wordpress Category Functions

Written By on in PHP

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

There are no comments for this post. Be the first!

 

Leave a Reply

Your email address will not be published.





If you find something abusive or that does not comply with our terms or guidelines please flag it as inappropriate.

Copyright © 2001-2018 Tim Trott, all rights reserved. Web Design by Azulia Designs

This web page is licensed for your personal, private, non-commercial use only.

Disclaimer, Privacy & LegalSitemapContact Me