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


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.

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.

  • So i want something like this: If currently displayed category is child category of "foo" include "foo.css" elseif, is child of "cat2" include cat2.css, else include style.css (default style for categories). My current code for this is pastebin.com/Cvh6R2ms and works only for posts, not categories Jan 24 '11 at 11:46
  • Could you please explain styling category page "foobar" better? Do you mean archive of foobar category? Something else?
    – Rarst
    Jan 24 '11 at 11:50
  • Yes Rarst, i want to change stylings of all posts, categories and category "foo" with my foo.css style. Also, i want to style all posts, categories and posts in category "cat2" and so on. Check my previous comment with pastebin link, there is some code i shared there. Jan 24 '11 at 11:54

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.


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 {


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.