Skip to content

Instantly share code, notes, and snippets.

@seothemes
Created May 9, 2017 14:35
Show Gist options
  • Save seothemes/4cc605866d12a68ea5a520a8dfb628af to your computer and use it in GitHub Desktop.
Save seothemes/4cc605866d12a68ea5a520a8dfb628af to your computer and use it in GitHub Desktop.
Dynamic widget areas
<?php
/**
* Register setting and control with the Customizer.
*/
function dynamic_customizer_register( $wp_customize ) {
// Add setting.
$wp_customize->add_setting(
'dynamic_widget_areas',
array(
'default' => 5,
'sanitize_callback' => 'sanitize_text_field',
'type' => 'option',
'transport' => 'refresh',
)
);
// Add control
$wp_customize->add_control(
'dynamic_widget_areas',
array(
'type' => 'number',
'label' => __( 'Front Page Widget Areas', 'theme-name' ),
'description' => __( 'Select the number of widget areas to display on the front page.', 'theme-name' ),
'section' => 'static_front_page',
'settings' => 'dynamic_widget_areas',
)
);
}
add_action( 'customize_register', 'dynamic_customizer_register' );
<?php
/**
* Dynamic front page widget areas.
*/
function dynamic_front_page_widgets() {
$front_page_widgets = get_option( 'dynamic_widget_areas', 5 );
// Loop through and display widget areas.
for ( $i = 1; $i <= $front_page_widgets; $i++ ) {
genesis_widget_area( "front-page-$i", array(
'before' => "<div class='front-page-$i'><div class='wrap'>",
'after' => '</div></div>',
) );
}
}
<?php
// Conditional variable of front page widgets. (Dynamic widget areas workaround).
$dynamic_widget_areas = is_customize_preview() ? 20 : get_option( 'dynamic_widget_areas', 5 );
// Register dynamic front page widget areas.
for ( $i = 1; $i <= $dynamic_widget_areas; $i++ ) {
genesis_register_sidebar( array(
'id' => 'front-page-' . $i,
'name' => __( 'Front Page ', 'theme-name' ) . $i,
'description' => __( 'This is the front page ', 'theme-name' ) . $i . __( ' widget area.', 'theme-name' ),
) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment