• Resolved alby54

    (@alby54)


    Hi, I need to do what the title explains.. so I’ve tried this code in single.php

    <?php $category = get_the_category();
        if ($category[0]->category_parent = 'approfondimenti') {
    
    	get_header('regular-approfondimenti'); 
    
    	} elseif ($category[0]->category_parent = 'le-tue-campagne-salute') {
    
    	get_header('regular-le-tue-campagne-salute');	
    
    	} else { get_header(); }	?>

    The first condition works but the second is totally ignored and the first header gets loaded instead. What am I doing wrong? Thanks for your help.

Viewing 3 replies - 1 through 3 (of 3 total)
  • C W (VYSO)

    (@cyril-washbrook)

    Conditional statements work sequentially. If the if statement returns true, then the elseif and else statements are ignored. This is because they are alternatives: they are only tested if the earlier condition is not met. Hence the term “else”.

    If you want the second condition to have priority, you need to make it the first condition.

    none of the conditions use the correct syntax;

    https://php.net/manual/en/language.operators.comparison.php

    also, $category[0]->category_parent would be a category ID, not the slug …

    Thread Starter alby54

    (@alby54)

    Ok, I solved the problem using this code in functions.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;
        }
    }

    and placing this other code in single.php

    if ( in_category( 'approfondimenti' ) || post_is_in_descendant_category( 24 ) ) {
    get_header('regular-approfondimenti'); 
    
    	} elseif ( in_category( 'le-tue-campagne-salute' ) || post_is_in_descendant_category( 25 ) ) {
    
    	get_header('regular-le-tue-campagne-salute');	
    
    	} else { get_header('regular'); }

    where 24 and 25 are the ID of the two categories…and it worls like a charm. Thanks anyway.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Load different headers based on post parent category’ is closed to new replies.