The deactivate_{$plugin} WordPress PHP action fires as a specific plugin is being deactivated. It is used internally by register_deactivation_hook()
and the dynamic part of the hook name, $plugin
, refers to the plugin basename. Note that if a plugin is silently deactivated (e.g., during an update), this hook will not fire.
Usage
add_action('deactivate_plugin_slug', 'your_deactivation_function'); function your_deactivation_function($network_deactivating) { // your custom code here }
Parameters
$network_deactivating
(bool): Whether the plugin is deactivated for all sites in the network or just the current site. This parameter is for multisite installations only. Default is false.
More information
See WordPress Developer Resources: deactivate_{$plugin}
Examples
Clean up options on plugin deactivation
Remove custom plugin options from the database when the plugin is deactivated.
add_action('deactivate_my_plugin', 'my_plugin_cleanup'); function my_plugin_cleanup($network_deactivating) { delete_option('my_plugin_option'); }
Deactivate a custom post type
Remove a custom post type when the plugin is deactivated.
add_action('deactivate_my_plugin', 'my_plugin_remove_post_type'); function my_plugin_remove_post_type($network_deactivating) { unregister_post_type('my_custom_post_type'); }
Remove custom roles and capabilities
Clean up custom roles and capabilities when the plugin is deactivated.
add_action('deactivate_my_plugin', 'my_plugin_remove_roles_and_caps'); function my_plugin_remove_roles_and_caps($network_deactivating) { remove_role('my_custom_role'); $role = get_role('editor'); $role->remove_cap('my_custom_capability'); }
Flush rewrite rules
Flush rewrite rules when the plugin is deactivated to remove custom rewrite rules added by the plugin.
add_action('deactivate_my_plugin', 'my_plugin_flush_rewrite_rules'); function my_plugin_flush_rewrite_rules($network_deactivating) { flush_rewrite_rules(); }
Log plugin deactivation
Log the plugin deactivation in a custom log file.
add_action('deactivate_my_plugin', 'my_plugin_log_deactivation'); function my_plugin_log_deactivation($network_deactivating) { $log_message = "Plugin deactivated on: " . date('Y-m-d H:i:s') . PHP_EOL; file_put_contents(plugin_dir_path(__FILE__) . 'my_plugin_log.txt', $log_message, FILE_APPEND); }