7

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()?

1 Answer 1

16

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);
3
  • However this does return widgets from plugins, this does not seem to return any custom registered widgets Jun 15, 2017 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, 2018 at 14:38
  • This returns all widgets even from deactivated themes. Is there a way to return only available widgets from the current active theme?? Please help Jul 2, 2023 at 6:43

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .