function clearwidgets(){
//stuff here only runs once, when the theme is activated for the 1st time
}
register_activation_hook(__FILE__, 'clearwidgets');
And the code I am trying to execute is this:
add_filter( 'sidebars_widgets', 'unset_sidebar_widget' );
function unset_sidebar_widget( $sidebars_widgets ) {
unset( $sidebars_widgets[ '$sidebar_id' ] );
return $sidebars_widgets;
}
That means when the first time the theme is installed it should clear away all the default widget set by WordPress.
Where am I going wrong because the desired result is not achieved? Please suggest me the fix or direct me in the direction so that I can troubleshoot.
function clearwidgets(){
//stuff here only runs once, when the theme is activated for the 1st time
}
register_activation_hook(__FILE__, 'clearwidgets');
And the code I am trying to execute is this:
add_filter( 'sidebars_widgets', 'unset_sidebar_widget' );
function unset_sidebar_widget( $sidebars_widgets ) {
unset( $sidebars_widgets[ '$sidebar_id' ] );
return $sidebars_widgets;
}
That means when the first time the theme is installed it should clear away all the default widget set by WordPress.
Where am I going wrong because the desired result is not achieved? Please suggest me the fix or direct me in the direction so that I can troubleshoot.
Share Improve this question asked Jun 24, 2019 at 6:54 WordCentWordCent 1,9066 gold badges34 silver badges60 bronze badges 8 | Show 3 more comments1 Answer
Reset to default 2What about using WordPress Options API to store a flag whether it is the first switch or not: https://codex.wordpress/Options_API
<?php
add_action('after_switch_theme', 'setup_theme_options');
function setup_theme_options () {
if(get_option('first_theme_activation') === false){
// Set a flag if the theme activation happened
add_option('first_theme_activation', true, '', false);
// stuff here only runs once, when the theme is activated for the 1st time
}
}
Going back to Jacob Peattie's note, register_activation_hook()
is for plugin use and not for theme switching. And unsetting content could become tricky, because you don't know what is there.
Either way, I hope this answers helps!
register_activation_hook()
is only for plugin activation. To handle activation of themes, use theafter_switch_theme
hook. With regards to widgets, how do you know they're the default? I suggest leaving people's content alone when activating your theme. If you want to show of what your theme can look like, consider using the Starter Content feature: make.wordpress/core/2016/11/30/… – Jacob Peattie Commented Jun 24, 2019 at 7:08