‘if/elseif’ and ‘is_active_sidebar’ statement in WordPress theme

I have this code:

<?php if ( is_active_sidebar('lt') && is_active_sidebar('rt')) { ?>

  <div class="grid_6 eqh">

<?php } elseif ( !is_active_sidebar('lt') || !is_active_sidebar('rt')) { ?>

  <div class="grid_9 eqh">

<?php } elseif ( !is_active_sidebar('lt') && !is_active_sidebar('rt')) { ?>

  <div class="grid_12 eqh">

<?php }; ?>

It’s part of a wordpress theme I’m developing. It’s supposed to show different classes according to a sidebar being active or not. The response I get from wp if a sidebar is active is 1 and NULL if it isn’t. It works if the ‘lt’ sidebar is active, but the ‘rt’ is not, it diplays the ‘grid_9’ div, if none of the sidebars is active, it displays the ‘grid_12’ div, but if the ‘rt’ sidebar is inactive and the ‘lt’ is active, it still displays the ‘grid_6’ div. If I remove the 1st if statement:

Read More
<?php if ( is_active_sidebar('lt') && is_active_sidebar('rt')) { ?>

it doesn’t display any of the divs.

I’ve tried every combination that came to my mind, I’ve separated the:

<?php } elseif ( !is_active_sidebar('lt') || !is_active_sidebar('rt')) { ?>

statement in 2 different ones, tried separate if statements without ‘elseif’, tried with, ‘AND’ and ‘OR’ instead of ‘&&’ and ‘||’ and a whole bunch of other variations, but nothing worked.

If anyone can help me or at least pont me in the right direction, I’d be very grateful.

As per @one-trick-pony ‘s suggestion, code is now:

<?php
$ltActive = is_active_sidebar('lt');
$rtActive = is_active_sidebar('rt');

if($ltActive && $rtActive){
  $class = 'grid_6';

}elseif(!$ltActive && !$rtActive){
  $class = 'grid_12';

}else{
  $class = 'grid_9';      // <==
}
?>

<div class="<?php echo $class; ?> eqh">

The php code is working, but it seems there is a bug with the is_active_sidebar() function in WP, but they are ignoring my question on the WP support forum.

Related posts

Leave a Reply

1 comment

  1. First, put the return result in variables (it will speed up processing a little):

    $ltActive = is_active_sidebar('lt');
    $rtActive = is_active_sidebar('rt');
    

    Now, the problem is in your 2nd condition – you’re checking if any of the sidebars are inactive, and if one of them or both are, the 3rd condition will never be evaluated.

    So:

    (!$ltActive && !$rtActive)
    

    must go before:

    (!$ltActive || !$rtActive)
    

    (last condition will not be necessary, you can just leave else{...})


    Ok here’s the code:

    if($ltActive && $rtActive){
      $class = 'class when both sidebars are active';
    
    }else(!$ltActive && !$rtActive){
      $class = 'class when both sidebars are inactive';
    
    }else{
      $class = 'class when only one of the sidebars is active (either one)';      
    }
    
    ?>
    <div class="<?= $class; ?>">