• Sorry in advance for my bad english ??
    I am searching how to define a class to a parent category AND the childs categories.
    This is the code I’m using for the parent category :

    <h1 <?php
    if (is_category('fruits')) {echo 'class="fruits"';}
    if (is_category('vegetables')) {echo 'class="vegetables"';}
    ?>><?php echo single_cat_title(); ?>
    </h1>

    This code works fine for the parent category, of course. But how to define it ALSO for the subcategories ?
    Thank you in advance !!

Viewing 2 replies - 16 through 17 (of 17 total)
  • Thread Starter sottise

    (@sottise)

    YEAY ! Finally, it works !!

    I used the code mentioned here .

    <?php
    if ( ! function_exists( 'post_is_in_descendant_category' ) ) {
    	function post_is_in_descendant_category( $cats, $_post = null ) {
    		foreach ( (array) $cats as $cat ) {
    			// get_term_children() accepts integer ID only
    			$descendants = get_term_children( (int) $cat, 'category' );
    			if ( $descendants && in_category( $descendants, $_post ) )
    				return true;
    		}
    		return false;
    	}
    }
    ?>
    <h1 <?php if ( in_category( 'fruits' ) || post_is_in_descendant_category( ID ) ) {echo 'class="fruits"';}
    	  if ( in_category( 'vegetables' ) || post_is_in_descendant_category( ID ) ) {echo 'class="vegetables"';}
    	  	?>><?php the_category(' / '); ?></h1>

    Happy me ??
    Anyway, thank you so much for your help cykeltomte, I really appreciated it ! ??

    Well, not sure if I really contributed with anything helpful, but I’m glad you solved it ??

Viewing 2 replies - 16 through 17 (of 17 total)
  • The topic ‘How to define a class to category AND subcategory’ is closed to new replies.