Using WordPress ‘register_deactivation_hook()’ PHP function

The register_deactivation_hook() WordPress PHP function sets the deactivation hook for a plugin.

Usage

register_deactivation_hook( string $file, callable $callback );

Example:

register_deactivation_hook( __FILE__, 'my_plugin_deactivate' );

Parameters

  • $file (string) – The filename of the plugin, including the path.
  • $callback (callable) – The function hooked to the ‘deactivate_PLUGIN’ action.

More information

See WordPress Developer Resources: register_deactivation_hook

Examples

Basic Plugin Deactivation

This example demonstrates how to call the my_plugin_deactivate function when the plugin is deactivated.

function my_plugin_deactivate() {
    // Your deactivation logic here
}

register_deactivation_hook( __FILE__, 'my_plugin_deactivate' );

Plugin Deactivation with Namespace

This example demonstrates how to use the register_deactivation_hook function with a namespace.

namespace MyNamespace;

function deactivate_plugin() {
    // Your deactivation logic here
}

register_deactivation_hook( __FILE__, __NAMESPACE__ . '\\deactivate_plugin' );

Clearing Transients on Deactivation

This example demonstrates how to clear transients when the plugin is deactivated.

function clear_plugin_transients() {
    delete_transient( 'my_plugin_transient_key' );
}

register_deactivation_hook( __FILE__, 'clear_plugin_transients' );

Removing Custom Database Table

This example demonstrates how to remove a custom database table when the plugin is deactivated.

function remove_custom_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'my_custom_table';

    $wpdb->query( "DROP TABLE IF EXISTS {$table_name}" );
}

register_deactivation_hook( __FILE__, 'remove_custom_table' );

Removing Custom Post Type

This example demonstrates how to remove a custom post type when the plugin is deactivated.

function remove_custom_post_type() {
    unregister_post_type( 'my_custom_post_type' );
    flush_rewrite_rules();
}

register_deactivation_hook( __FILE__, 'remove_custom_post_type' );