0
    $sidebars = array(
            is_active_sidebar( 'footer-4' ),
            is_active_sidebar( 'footer-3' ),
            is_active_sidebar( 'footer-2' ),
            is_active_sidebar( 'footer-1' ),
    );

    $col = 0;

    foreach ( $sidebars as $sidebar ) {

        if ( $sidebar ) {
            $col++;
        }

    }

    echo 'col-'.$col.'';

What i am trying to accomplish is have the correct number of WordPress active sidebars outputted. So that they can be styled with css example: if 3 sidebars are active you get col-3 if (1) if you col-1.

The code above works. My concern is can it be improved, is this the right way to do it ? Or can increments be used for example: $i = 0; $i++; instead of an array.

Thanks.

1

Use the array_filter() function, which will remove every array element that has false as the value. Then you can count the array length. So your example would look like this:

$sidebars = array(
        is_active_sidebar( 'footer-4' ),
        is_active_sidebar( 'footer-3' ),
        is_active_sidebar( 'footer-2' ),
        is_active_sidebar( 'footer-1' ),
);

$active_sidebars = array_filter($sidebars);

echo 'col-'.count($active_sidebars);
0

From the Wordpress Codex: is_active_sidebar()

This Conditional Tag checks if a given sidebar is active (in use). This is a boolean function, meaning it returns either TRUE or FALSE.

Any sidebar that contains widgets will return TRUE, whereas any sidebar that does not contain any widgets will return FALSE.

So you should be able to do something like this:

$col = 0;

if( is_active_sidebar( 'footer-4' ) ) $col++;
if( is_active_sidebar( 'footer-3' ) ) $col++;
if( is_active_sidebar( 'footer-2' ) ) $col++;
if( is_active_sidebar( 'footer-1' ) ) $col++;

echo 'col-'.$col;

Or maybe even:

$col = 0;

for ($i = 1; $i <= 4; $i++) {
  if( is_active_sidebar( 'footer-'.$i ) ) $col++;
}

echo 'col-'.$col;

NOTE: I've not had time to test either of these methods.

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.