Is Post in a Descendant Category?

Posted on

By Michael Fields

If you are using the built-in Category Hierarchy to organize your posts, you might find yourself in a situation where you will need to execute code for all posts that are in a descendant category of a given parent category.

<?php
if( !function_exists( 'mfields_post_is_in_descendant_category' ) ) {
    /*
    * Post is in Descendant Category
    * Copyright 2009 Michael Fields
    * @license: GPL 2
    * @param $cats array - an indexed array of category ids.
    * @param $post_id int - optional specify a specific $post->ID to test for.
    * @return bool
    */
    function mfields_post_is_in_descendant_category( $cats, $post_id = null ) {
        if( is_array( $cats ) ) {
            foreach ( ( array ) $cats as $cat ) {
                $descendants = get_term_children( ( int ) $cat, 'category' );
                if ( $descendants && in_category( $descendants, $post_id ) )
                    return true;
            }
        }
        return false;
    }
}

/* Example Usage */
if( mfields_post_is_in_descendant_category( array( 25, 132, 543 ) ) ) {
    /* Do Stuff Here... */
}
?> 

1 Comment Leave a comment

  1. Isaac Foxx September 15, 2010 at 3:33 am

    ive been attempting to do the same thing with custom post types in a custom taxonomy term but I was not able to modify the code to accomplish it since i suck at php. have you attempted to do the same thing? I really appreciate the other snippets you’ve posted.

Share your thoughts

*

Fork me on GitHub