Written by Sean Behan on Sun Jun 17th 2012

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

  the_child_categories("Vermont");
  // 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;
  endif;
endforeach;
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 : '';
      endforeach;
    endif;
  endif;
}

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 with..
#api #children #functionality #get_categories #parent #Wordpress #Programming #Wordpress

Just finishing up brewing up some fresh ground comments...