5

I'm trying to disable a couple standard widgets in my theme functions.php. Therefore I wrote this little function, which works well:

function my_widget_ctrl() {
     unregister_widget('WP_Widget_Pages');
     unregister_widget('WP_Widget_Calendar');
     unregister_widget('WP_Widget_Archives');
     unregister_widget('WP_Widget_Links');
     unregister_widget('WP_Widget_Meta');        
     unregister_widget('WP_Widget_Text');       
     unregister_widget('WP_Widget_Recent_Posts');
     unregister_widget('WP_Widget_Recent_Comments');
     unregister_widget('WP_Widget_RSS');
     unregister_widget('WP_Widget_Tag_Cloud');        

 }
 add_action('widgets_init', 'my_widget_ctrl', 11);

Now I want to disable some other Widgets, which may be installed/activated by other Plugins. But I don’t know how to get a list of all widget-class-names registered, so I can unregister them with unregister_widget()?

10

Widgets are stored in a public variable $widgets in the class WP_Widget_Factory. You can access this class per global variable $wp_widget_factory.

To get all registered widgets, list the keys:

add_action( 'wp_footer', function()
{
    if ( empty ( $GLOBALS['wp_widget_factory'] ) )
        return;

    $widgets = array_keys( $GLOBALS['wp_widget_factory']->widgets );
    print '<pre>$widgets = ' . esc_html( var_export( $widgets, TRUE ) ) . '</pre>';
});

To remove all widgets either unregister each widget separately with unregister_widget() (preferred) or empty the array in one run:

add_action( 'widgets_init', function()
{
    if ( empty ( $GLOBALS['wp_widget_factory'] ) )
        return;

    $GLOBALS['wp_widget_factory']->widgets = array();
}, 20);
  • However this does return widgets from plugins, this does not seem to return any custom registered widgets – Derk Jan Speelman Jun 15 '17 at 12:46
  • @DerkJanSpeelman this is probably because they are registered later, but hopefully during the same widget_init action. Try changing the priority from 20 to 100 or even 1000 and see what you get. Good plugins/themes/code should always register their widgets during widget_init. – Anastis Jan 25 '18 at 14:38

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.