13

I'm listing all sidebars like that:

global $wp_registered_sidebars;

echo '<pre>';
print_r($wp_registered_sidebars); 
echo '</pre>'

So I'm getting something like:

Array
(
    [sidebar-1] => Array
        (
            [name] => Sidebar #1
            [id] => sidebar-1
            [description] => Sidebar number 1
            [before_widget] => 
            [after_widget] => 
            [before_title] => 
            [after_title] =>
        )

 (...)

)

But I'd love to display them as a select list, like:

<select>
  <option value ="SIDEBAR-ID">SIDEBAR-NAME/option>
  <option value ="SIDEBAR-ID">SIDEBAR-NAME/option>
(...)
</select>

Wordpress Codex isn't helpful at all.

Thank you!

  • Where exactly are you listing the sidebars and what purpose does this serve? – kaiser Apr 2 '11 at 13:10
21

Loop through the global:

<select>
<?php foreach ( $GLOBALS['wp_registered_sidebars'] as $sidebar ) { ?>
     <option value="<?php echo ucwords( $sidebar['id'] ); ?>">
              <?php echo ucwords( $sidebar['name'] ); ?>
     </option>
<?php } ?>
</select>

Note:
The ucwords() function is only there to display it exactly as you asked. Not sure if you really want that.


How to access global arrays & objects:

Anyway: Your Q mostly is about how to access arrays. I wrote a Q about that (for further explanation). Please take a look over here.

6

Write a function to create the list for you?

function sidebar_selectbox( $name = '', $current_value = false ) {
    global $wp_registered_sidebars;

    if ( empty( $wp_registered_sidebars ) )
        return;

    $name = empty( $name ) ? false : ' name="' . esc_attr( $name ) . '"';
    $current = $current_value ? esc_attr( $current_value ) : false;     
    $selected = '';
    ?>
    <select<?php echo $name; ?>>
    <?php foreach ( $wp_registered_sidebars as $sidebar ) : ?>
        <?php 
        if ( $current ) 
            $selected = selected( $current === $sidebar['id'], true, false ); ?>    
        <option value="<?php echo $sidebar['id']; ?>"<?php echo $selected; ?>><?php echo $sidebar['name']; ?></option>
    <?php endforeach; ?>
    </select>
    <?php
}

Then just call it wherever you need to create a select list with the sidebars, optionally passing in a name, eg.

sidebar_selectbox();

or

sidebar_selectbox( 'theme_sidebars' );

Additionally and optionally, pass in a currently selected value...

sidebar_selectbox( 'theme_sidebars', $var_holding_current );

Hope that helps.

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.