WordPress.org

Ready to get started?Download WordPress

Forums

If In Subcategory (4 posts)

  1. obeattie
    Member
    Posted 8 years ago #

    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

  2. obeattie
    Member
    Posted 8 years ago #

    Bump?

  3. Mark Jaquith
    WordPress Lead Dev
    Posted 8 years ago #

    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);
    }

  4. Mark Jaquith
    WordPress Lead Dev
    Posted 8 years ago #

Topic Closed

This topic has been closed to new replies.

About this Topic