0
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.

8
  • are you trying to remove some available default widget options or clear the existing widget instances saved to existing theme sidebars? because the 2nd is unnecessary I am guessing it is the first?
    – majick
    Jun 24, 2019 at 7:04
  • register_activation_hook() is only for plugin activation. To handle activation of themes, use the after_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.org/core/2016/11/30/… Jun 24, 2019 at 7:08
  • No when you install any theme for the first time. WordPress throw its default widgets in the posts sidebar(single posts). I want to get rid of them during theme's first activation. Jun 24, 2019 at 7:21
  • Can you suggest final corrected code to achieve what i am trying 2 achieve? Jun 24, 2019 at 7:22
  • "how do you know they're the default? " thats why I want to do this only once when the theme is activated for the first time? Jun 24, 2019 at 7:28

1 Answer 1

2

What about using WordPress Options API to store a flag whether it is the first switch or not: https://codex.wordpress.org/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!

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.