Collection of Useful Wordpress Category Functions

A collection of useful Wordpress category functions. Get parent category, and detect if current category is a subcategory or child category.

By Tim Trott | WordPress | January 24, 2009

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

Get Parent Category ID

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

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

Is Post in Category or Sub Category of Specified 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.

php
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.

Prevent WordPress Showing Posts of Sub Categories

In some types of website, you may wish to display ONLY the posts of a category and not posts of sub categories on a Wordpress blog. Let's say you had a parent category of "Weather" with sub-categories "America" and "United Kingdom". When a user clicks on the weather category, Wordpress will automatically display posts from the Weather category AS WELL AS the posts of America and the United Kingdom.

If this is not the behaviour you are after, there is a template tag trick that you can use in your theme to show posts of the current category ONLY.

If you have an archive.php or category.php open that, otherwise open index.php. Don't forget to back them up just in case things go wrong!

Find the line similar to (start of the loop):

php
<?php while (have_posts()) : the_post(); ?>

and add after it on the next line:

php
<? if ((is_category()) && in_category($wp_query->get_queried_object_id())) { ?>

This line checks if we are viewing a category and that the post being processed is a member of the category being viewed. If it is then we will show the post.

$wp_query->get_queried_object_id() returns an integer ID of the category being viewed.

in_cagegory() tests if the current post in the loop is a member of the specified category, in this case, we pass it the current category.

Next need to find the line:

php
<?php endwhile; ?>

Which is the end of the loop, and add a line BEFORE it containing:

php
<?php } ?>

This small modification will stop posts of child categories from showing when a parent category is selected. Of course, you will need some posts in Weather otherwise you will have a blank page. You can also use the information on the Wordpress Codex template tags to create static pages for each category if you wish.

If you only wish to stop sub-category posts from showing on one particular parent category you can specify the required category in the is_category() method. Simply insert the numerical id of the parent category in the brackets, e.g. is_category(10) will stop sub-category posts from showing only if we are viewing the category with ID of 10. All other categories will retain their default setting.

Was this article helpful to you?
 

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

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.

This post has 16 comment(s). Why not join the discussion!

We respect your privacy, and will not make your email public. Learn how your comment data is processed.

  1. JI

    On Sunday 3rd of June 2012, Jimako said

    Excellent! I tried a lot of plugins for view posts only from parent category without sub, but when one post is in parent and child category, they weren't working. Thank you very much

  2. PH

    On Monday 8th of March 2010, php said

    hey dear
    the information u provide is not enough to solve my problems..
    pls explaine in detail...

  3. JA

    On Wednesday 16th of December 2009, jason said

    YES! After 3 hours searching this nails it. (will have to be sure it doesn't paginate though!

    BTW for anyone who gets a fail: In the top code, you must change the & & to just one &

    get_queried_object_id())) { ?>

  4. KL

    On Friday 4th of September 2009, klimeklada said

    2feedme: thank you a lot!!

  5. FS

    On Monday 6th of April 2009, Falco Stellare said

    Nice solution, I really thank you for your tutorial!!!

  6. FE

    On Saturday 10th of January 2009, feedme said

    there is an issue when used with wp-pagenavi....

    it counts all the posts that return from the have_posts() function
    so it shows a blank page (or more) in pagenavi.

    i found this and its working.

    http://wordpress.org/extend/plugins/just-one-category/

    sorry for my english.

    1. CL

      On Saturday 11th of December 2010, clubmid replied

      Thanx it really works, I have been looking for a solution for quire some time...

  7. RA

    On Thursday 8th of January 2009, rat said

    thank you. solved all my problems

  8. JO

    On Tuesday 23rd of December 2008, joe said

    Perfect! only one addition, how to display one of the categories just one? thank you so much.

  9. CB

    On Monday 24th of November 2008, CBSE said

    Finally.. I got it.. Thank you so much dude.. I was looking for this for about two weeks.

    Regards

  10. SS

    On Monday 27th of October 2008, Selim Saka said

    I was looking for this for over one month. Thank you. it worked for me.
    Perfect!

  11. JI

    On Monday 20th of October 2008, Jimmy said

    Worked perfect for me. I found the code in archive.php -> themes folder.

  12. AN

    On Thursday 17th of July 2008, Andy said

    Yep, didn&squot;t work for me either...

  13. RI

    On Wednesday 7th of May 2008, Richard said

    causes a fatal error in category.php in V 2.51 Any ideas??

    thanks

  14. EV

    On Monday 17th of March 2008, Everett said

    I tried this fix but then the first page of every main category was blank. The &quot;next&quot; page would show entries that were inside that main category, but for some reason the first page still showed up without any posts on it. ???

    1. AS

      On Saturday 10th of April 2010, ashley replied

      Works fine on all the sub categories but the main category is blank, any ideas?