Using WordPress ‘delete_widget’ PHP action

The delete_widget WordPress PHP action fires immediately after a widget has been marked for deletion.

Usage

add_action('delete_widget', 'my_custom_delete_widget_function', 10, 3);

function my_custom_delete_widget_function($widget_id, $sidebar_id, $id_base) {
    // your custom code here
}

Parameters

  • $widget_id: string – ID of the widget marked for deletion.
  • $sidebar_id: string – ID of the sidebar the widget was deleted from.
  • $id_base: string – ID base for the widget.

More information

See WordPress Developer Resources: delete_widget

Examples

Log widget deletion

Log the deletion of a widget for debugging purposes.

add_action('delete_widget', 'log_widget_deletion', 10, 3);

function log_widget_deletion($widget_id, $sidebar_id, $id_base) {
    error_log("Widget ({$widget_id}) with ID base ({$id_base}) deleted from sidebar ({$sidebar_id}).");
}

Remove any related data stored in the database when a widget is deleted.

add_action('delete_widget', 'remove_widget_related_data', 10, 3);

function remove_widget_related_data($widget_id, $sidebar_id, $id_base) {
    // Delete related data for the widget
    delete_option("my_plugin_widget_{$widget_id}_data");
}

Send an email notification

Send an email notification to the admin when a widget is deleted.

add_action('delete_widget', 'send_widget_deletion_notification', 10, 3);

function send_widget_deletion_notification($widget_id, $sidebar_id, $id_base) {
    $admin_email = get_option('admin_email');
    $subject = "Widget Deleted: {$widget_id}";
    $message = "The widget with ID: {$widget_id}, ID base: {$id_base} has been deleted from the sidebar: {$sidebar_id}.";
    wp_mail($admin_email, $subject, $message);
}

Update widget count

Update a custom widget counter when a widget is deleted.

add_action('delete_widget', 'update_widget_count', 10, 3);

function update_widget_count($widget_id, $sidebar_id, $id_base) {
    $count = get_option('my_plugin_widget_count', 0);
    update_option('my_plugin_widget_count', $count - 1);
}

Trigger a custom action

Trigger a custom action when a specific widget is deleted.

add_action('delete_widget', 'trigger_custom_action', 10, 3);

function trigger_custom_action($widget_id, $sidebar_id, $id_base) {
    if ($id_base === 'my_custom_widget') {
        do_action('my_custom_widget_deleted', $widget_id, $sidebar_id);
    }
}