List all sidebar names?

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!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x