now available

now available
Want fresh tech tips in your inbox?

Get Child Categories of Parent Category on Single Post in Wordpress


I was hoping to find a function in the Wordpress API, that goes something like this...

  // print Burlington, Brattleboro... etc if this post has any child categories of Vermont

But I could not. The result that I did find, from various forums goes something like this...

$parentcat = get_category_by_slug('Vermont');
foreach((get_the_category()) as $childcat):
  if (cat_is_ancestor_of($parentcat, $childcat)):
    echo get_category_link($childcat->cat_ID);
    echo $childcat->cat_name;
If you're in the in the Loop, you can use the get_the_category() function to retrieve the category objects of the current post, without printing the results to the screen. You can loop over the contents from what is returned by the function.

This condition uses the API function "cat_is_ancestor_of" to check whether or not the category from the current post is a child of the parent which we fetched with the "get_category_by_slug" function.

Here is a little function that I threw into "functions.php" so that I can get the child categories easily in my theme.

/* Usage
_the_category_children("Vermont"); /
function _the_category_children($slug=""){
  if($categories       = get_the_category()):
    if($slug_category   = get_category_by_slug($slug)):
      foreach($categories as $category):
        echo (cat_is_ancestor_of($slug_category, $category)) ? $category->cat_name : '';

More info/references on accomplishing this functionality are available http://codex.wordpress.org/Function_Reference/cat_is_ancestor_of http://wordpress.org/support/topic/284057?replies=8#post-1120489 http://wordpress.org/support/topic/297615

Tagged w/ #api #children #functionality #get_categories #parent #wordpressprogramming #wordpress

Apps I've Built

XPath Expression Editor
Practice and improve your XPath skills with XPath Editor
Click to buy on the App Store
Photo Location Changer
Easily change the location on your photos and videos
Click here for more info about the app
Photo Date Changer
Easily change the dates and times on your photos and videos
Click here for more info about the app
English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app