Here is the code on how to delete all dashboard widgets – the default, and plugin widgets but I want to change the code to only delete custom dashboard widgets not the default ones.


// Create the function to use in the action hook
function remove_dashboard_widgets() {
    global $wp_meta_boxes;
    if ( !array( $wp_meta_boxes ) ) return;
    foreach ( $wp_meta_boxes as $widget_section => $widget_locations ) {
        if ( $widget_section == 'dashboard' ) {
            foreach ( $widget_locations as $widget_location => $widget_types ) {
                foreach ( $widget_types as $widget_type => $widgets ) {
                    foreach ( $widgets as $widget_name => $widget ) {
                        remove_meta_box( $widget_name, $widget_section, $widget_location );
                    }               
                }
            }
        }
    }
} 
// Hook into the 'wp_dashboard_setup' action to register our function
add_action('wp_dashboard_setup', 'remove_dashboard_widgets', 11 );

2 Answers
2

The built-in dashboard widgets are not marked somehow, you have to use a fixed list:

'dashboard_right_now',
'dashboard_plugins',
'dashboard_quick_press',
'dashboard_recent_drafts',
'dashboard_recent_comments',
'dashboard_incoming_links',
'dashboard_primary',
'dashboard_secondary'

So your code should test if the current widget is in that list and remove the widget, if it isn’t:

add_action(
    'wp_dashboard_setup',
    't5_remove_custom_dashboard_widgets',
    11
);

function t5_remove_custom_dashboard_widgets()
{
    global $wp_meta_boxes;

    $builtin = array (
        'dashboard_right_now',
        'dashboard_plugins',
        'dashboard_quick_press',
        'dashboard_recent_drafts',
        'dashboard_recent_comments',
        'dashboard_incoming_links',
        'dashboard_primary',
        'dashboard_secondary'
    );

    if ( empty ( $wp_meta_boxes['dashboard'] ) )
        return;

    $widget_groups = $wp_meta_boxes['dashboard'];

    foreach ( $widget_groups as $section => $widget_group )
        foreach ( $widget_group as $widgets )
            foreach ( $widgets as $id => $widget )
                if ( ! in_array( $id, $builtin ) )
                    remove_meta_box( $id, 'dashboard', $section );
}

Leave a Reply

Your email address will not be published. Required fields are marked *