Dynamic Sidebar
<?php
class Dynamic_Sidebars {
private $i;
private $sidebars;
function __construct(){
add_action( 'widgets_init', array( $this, 'init' ) );
}
function init() {
$this->sidebars = apply_filters('dynamic_sidebars', array());
$sidebars = $this->sidebars;
foreach ( $sidebars as $name => $sidebar ) {
$id = $this->slugify( $name );
register_sidebar( array(
'name' => __( $name, 'dynamic_sidebar' ),
'id' => "$id-sidebar",
'description' => __( $sidebar['description'], 'dynamic_sidebar' ),
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h4 class="widgettitle">',
'after_title' => '</h4>',
) );
add_action($sidebar['action'], array( $this, 'print_sidebar' ), $sidebar['priority']);
}
}
function print_sidebar($name) {
$id = $this->slugify($name);
$active = is_active_sidebar( "$id-sidebar" );
if ( $active ) {
?>
<div id="<?php echo $id; ?>" class="<?php echo $id; ?>">
<div class="container">
<div class="row">
<?php dynamic_sidebar( "$id-sidebar" ); ?>
</div>
</div>
</div>
<?php
}
}
function slugify( $string ) {
//Lower case everything
$string = strtolower($string);
//Make alphanumeric (removes all other characters)
$string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
//Clean up multiple dashes or whitespaces
$string = preg_replace("/[\s-]+/", " ", $string);
//Convert whitespaces and underscore to dash
$string = preg_replace("/[\s_]/", "-", $string);
return $string;
}
}
new Dynamic_Sidebars();