To improve user experience, you can display a one-time admin notice letting the site owner know that the plugin was deactivated because the required theme is no longer active.
The Code
Add this code below your deactivation function in the plugin’s main file:
php
// Show admin notice if plugin was deactivated due to theme change
add_action(‘admin_notices’, ‘my_plugin_theme_notice’);
function my_plugin_theme_notice() {
if (get_option(‘my_plugin_deactivated_due_to_theme’)) {
echo ‘<div class=”notice notice-warning is-dismissible”>’;
echo ‘<p><strong>My Plugin</strong> was automatically deactivated because the required theme is no longer active.</p>’;
echo ‘</div>’;
// Clean up the option so it only shows once
delete_option(‘my_plugin_deactivated_due_to_theme’);
}
}
// Save a flag before deactivation
register_deactivation_hook(__FILE__, function () {
$current_theme = wp_get_theme();
if ($current_theme->get(‘Name’) !== ‘MyTheme’) {
update_option(‘my_plugin_deactivated_due_to_theme’, true);
}
});
How It Works:
- register_deactivation_hook() runs when the plugin is deactivated. Here, we check if the reason is a theme mismatch and store a temporary flag in the database.
- admin_notices is used to hook into the admin panel and display the message.
- The flag is deleted right after showing the notice, so the message appears only once — no clutter or repeat messages.
Pro Tip: You can customize the notice message to include your plugin name, documentation link, or support info.
This feature adds a professional touch to your plugin and ensures users know exactly why the plugin was turned off.
Leave a Reply