What I am trying to do is pre-populate the sidebar widget area with some default widgets on theme activation.
if ( ! dynamic_sidebar( 'sidebar' ) ) :
does add the widgets but it doesnot show up in the sidebar of widgets section and
if ( is_active_sidebar( 'sidebar' ) ) {
this function doesnot work if the widgets are not loaded in the sidebar widgetized area.
I know it is possible but I am just out of idea. I googled but didnot find any solutions. Thank you for any help in advance.
It isn't clear from your answer if you use the after_switch_theme
hook but that the moment you need to set the widgets.
To activate the widgets I suggest writing it directly into the database with get_option('sidebars_widgets')
which should give an array, and save it with update_option('sidebars_widgets', $new_activated_widgets)
.
This should help you get started.
/**
* set new widgets on theme activate
* @param string $old_theme
* @param WP_Theme $WP_theme
*/
function set_default_theme_widgets ($old_theme, $WP_theme = null) {
// check if the new theme is your theme
// figure it out
var_dump($WP_theme);
// the name is (probably) the slug/id
$new_active_widgets = array (
'sidebar-name' => array (
'widget-name-1',
'widget-name-2',
'widget-name-3',
),
'footer-sidebar' => array(
'widget-name-1',
'widget-name-2',
'widget-name-3',
)
);
// save new widgets to DB
update_option('sidebars_widgets', $new_active_widgets);
}
add_action('after_switch_theme', 'set_default_theme_widgets', 10, 2);
Tested, just paste it in functions.php
of your theme.