If category is in parent category?

I have function that check what is main top category of post. So i have category tree like this

Foo
-bar
--foobar
cat2

and if post is in foobar, my function post_is_in_descendant_category shows me “foo” and i can style that post with style-foo.css. What i want now is to make this same possible for styling category page “foobar”. WordPress functions in_category works only for posts.

Read More

So, my code if ( in_category( 'foo' ) || post_is_in_descendant_category( get_term_by( 'name', 'foo', 'category' )) || is_category('56') ) doesn’t work for subcategories.

Related posts

Leave a Reply

2 comments

  1. If i understand right your “post_is_in_descendant_category” function checks if a post is descendant of a category and you want to check if a category is descentand. If so the add this function to your functions.php

    function is_desc_cat($cats, $_post = null) {
      foreach ((array)$cats as $cat) {
        if (in_category($cat, $_post)) {
          return true;
        } else {
          if (!is_int($cat)) $cat = get_cat_ID($cat);
          $descendants = get_term_children($cat, 'category');
          if ($descendants && in_category($descendants, $_post)) return true;
        }
      }
    
    return false;
    }
    

    and use it like this:

    if (is_desc_cat("foo")) {
      // use foo.css
    } else {
      // use default.css
    }
    

    Hope this helps.

  2. Try this:

    $cat_id = $wp_query->get_queried_object_id();
    $parents = explode( '/', get_category_parents( $cat_id, false ) );
    
    if( in_array( 'foo', $parents ) ) {
    
    }
    elseif( in_array( 'cat2', $parents ) ) {
    
    }
    else {
    
    
    }