Skip to content

Instantly share code, notes, and snippets.

@Firestorm-Graphics
Forked from c3mdigital/sidebar_select.php
Created June 11, 2012 21:53
Show Gist options
  • Save Firestorm-Graphics/2912982 to your computer and use it in GitHub Desktop.
Save Firestorm-Graphics/2912982 to your computer and use it in GitHub Desktop.
Sidebar Select Meta Box for cmb_meta_boxes
<?php
/**
* Adds a new sidebar_select field type to CMB Metaboxes
*
* Builds the select box from all registered sidebars.
* Use in themes to create per page or post layout options without having to create new templates
*
* @see https://github.com/jaredatch/Custom-Metaboxes-and-Fields-for-WordPress.git
*
*/
if ( is_admin() ) { // Optional is_admin check. I only include the metabox class on the admin side.
add_action( 'cmb_render_sidebar_select', 'wpu_sidebar_select', 10, 2 );
add_filter( 'cmb_validate_sidebar_select', 'wpu_validate_sidebar_select' );
}
/**
* Adds a custom field type to the meta box class
*
* @param array $field Your new field
* @param mixed $meta Current saved meta_value for the key
*/
function wpu_sidebar_select( $field, $meta ) {
$sidebars = $GLOBALS['wp_registered_sidebars'];
echo '<select name="', $field['id'], '" id="', $field['id'], '">';
foreach ($sidebars as $option) {
echo '<option value="', $option['id'], '"', $meta == $option['id'] ? ' selected="selected"' : '', '>', $option['name'], '</option>';
}
echo '</select>';
echo '<p class="cmb_metabox_description">', $field['desc'], '</p>';
}
/**
* Validation function for sidebar_select meta box field
*
* @param string $new The new value to validate before saving
* @return bool|string If validates returns the value
*/
function wpu_validate_sidebar_select( $new ) {
$sidebars = $GLOBALS['wp_registered_sidebars'];
if ( !array_key_exists( $new, (array)$sidebars ) ) $new ='';
return $new;
}
@Firestorm-Graphics
Copy link
Author

if using smof or options framework by devin then you can use the following in the options file (function.options.php in smof) to call in the registered sidebars as options,

            $of_sidebars = array();
    $of_sidebars_obj = $GLOBALS['wp_registered_sidebars'];
    foreach ($of_sidebars_obj as $option)
    {
        $of_sidebars[$option['id']] = $option['name'];

    }
    $sidebars_tmp = array_unshift($of_sidebars, "Select a sidebar:");

then in your chosen field type add "options" => $of_sidebars,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment