Website development and design blog, tutorials and inspiration

Useful Wordpress Category Functions

Wordpress Category Functions

By , Written on in PHP

Useful Wordpress Category Functions

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.

  1. function get_parent_category()
  2. {
  3. foreach ((get_the_category()) as $cat)
  4. {
  5. if ($cat->category_parent)
  6. return $cat->category_parent;
  7. else
  8. return $cat->cat_ID;
  9. }
  10. }

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.

  1. function in_category_or_subcategory_of($cat_id=0)
  2. {
  3. $cats = get_the_category();
  4. if (!count($cats))
  5. return false;
  6. foreach ((array)$cats as $cat)
  7. {
  8. if ($cat->cat_ID == $cat_id)
  9. return true;
  10. if (in_category_dig_parents($cat->category_parent, $cat_id))
  11. return true;
  12. }
  13. return false;
  14. }
  15.  
  16. function in_category_dig_parents($cat_id, $look_for)
  17. {
  18. if ( !$cat_id )
  19. return false;
  20. if ( $cat_id == $look_for )
  21. return true;
  22. $cat = get_category($cat_id);
  23. return in_category_dig_parents($cat->category_parent, $look_for);
  24. }

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

Further Reading
Comments

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

Leave a Reply

Your email address will not be published.