WordPress.org

Support

Support » How-To and Troubleshooting » If In Subcategory

If In Subcategory

  • Hey There,

    I am trying to fins a solution which checks if a post is in a category or a child of it.

    Basically, I want to display some text using a command which does something like ‘If this post is in $ category, or is in a child of it, do this’.

    I know how to use if(in_category('2') { to see if the post is in a certain category, but am unsure of how to do this so it includes children aswell.

    Any help would be most appreciated.

    Many Thanks in Advance,
    Oliver Beattie

Viewing 3 replies - 1 through 3 (of 3 total)
  • Bump?

    Moderator Mark Jaquith

    @markjaquith

    Put this in a hacks or plugin file. Then just do <?php if (in_category_recursive_up(24)) {

    It works by first checking the categories that they post has for a match. It then takes each category and “digs up” (basically asking each one, “who’s your daddy?”) until it either runs out of categories (false) or finds a match (true). I haven’t tested it too much, but initial tests indicate that it works.


    function in_category_recursive_up($cat_id=0) {
    if ( !is_single() )
    return false;
    $cats = get_the_category();
    if ( !count($cats) ) // error: no cats defined!
    return false;
    foreach ( (array) $cats as $cat ) {
    if ( $cat->cat_ID == $cat_id ) { // match!
    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);
    }

    Moderator Mark Jaquith

    @markjaquith

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘If In Subcategory’ is closed to new replies.