[wp-hackers] in_category does not seem to like child cats

Mark Jaquith mark.wordpress at txfx.net
Sat Jun 10 05:15:44 GMT 2006


On Jun 9, 2006, at 6:09 AM, Mark Harwood wrote:

> Im having a little trouble with in_category() it does not seem to  
> like to check for children cats. Is there any other built in  
> function in wordpress for checking if a post is IN or a CHILD of a  
> certain cat?

I actually started writing that code a few days ago, and was going to  
share with this list, but it slipped my mind.

> <?php
>
> function in_category_or_subcategory_of($cat_id=0) {
> 	$cats = get_the_category();
> 	if ( !count($cats) ) // error: no cats defined!
> 		return false;
> 	foreach ( (array) $cats as $cat ) {
> 		if ( $cat->cat_ID == $cat_id ) // is specifically in $cat_id
> 			return true;
> 		if ( in_category_dig_parents($cat->category_parent, $cat_id) ) //  
> is in a child of $cat_id
> 			return true;
> 	}
> 	return false;
> }
>
> function in_category_dig_parents($cat_id, $look_for) {
> 	if ( !$cat_id ) // we got to the top category, and there was no match
> 		return false;
> 	if ( $cat_id == $look_for ) // found $cat_id
> 		return true;
> 	$cat = get_category($cat_id);
> 	return in_category_dig_parents($cat->category_parent,  
> $look_for); // go up a level, and keep trying
> }
>
> ?>

The way it works is by checking each category that the post is in and  
"digging up" recursively from each one, checking the parents until it  
finds a match (or gets to the top of all category trees without  
finding a match).

This might be a good candidate for inclusion into core... it's  
certainly useful.  No longer do you have to check the parent cat and  
the child cat... you can just check the child cat and then use this  
function in your template logic.

--
Mark Jaquith
http://txfx.net/




More information about the wp-hackers mailing list