Function and usage of register_uninstall_hook() in wordpress


Answers ( 1 )


    The register_uninstall_hook() function in WordPress is an essential tool for plugin developers, allowing them to set up specific actions to be executed when a plugin is uninstalled. This function ensures that the plugin can clean up after itself, removing any settings, options, or other data it may have added to the WordPress database or filesystem, thereby maintaining the cleanliness and integrity of the website.

    Function Prototype:

    register_uninstall_hook( string $file, callable $callback )


    • Purpose: This function registers a hook that gets called during the uninstallation of a plugin. When a user decides to uninstall a plugin, WordPress looks for this hook to execute any cleanup or other necessary operations.
    • Behavior: The uninstall hook is only activated if the plugin explicitly registers it using register_uninstall_hook(). Without this registration, the uninstallation process will not trigger the custom cleanup operations defined in the hook.
    • Execution Context: It's important to note that this hook must not contain arbitrary code executed outside of functions. Since the plugin file is included during the uninstallation process, any code outside of a function would run during uninstallation, potentially causing unwanted behavior or hindering the process.
    • Alternative Method with uninstall.php: If a plugin's uninstallation logic cannot be contained within a hook (due to the necessity of running code within the plugin file), the developer should create an uninstall.php file in the base plugin folder. WordPress will execute this file instead of the uninstall hook, bypassing it. This file must check for the WP_UNINSTALL_PLUGIN constant before executing to ensure it's being called in the correct context.


    1. $file (string - required): The path to the main plugin file. This file typically contains the plugin header and initialization code.
    2. $callback (callable - required): A callable (like a function or static method name) that will be executed when the uninstall hook is triggered. This callable should contain the code to clean up the plugin's data.

    Sample Usage:

    // Registering an uninstall hook within a plugin
    function custom_plugin_cleanup() {
        // Code to delete plugin options, custom tables, etc.
    register_uninstall_hook( __FILE__, 'custom_plugin_cleanup' );

    In this example, custom_plugin_cleanup() is a function that would contain the logic to remove any custom settings or data that the plugin has created in the WordPress database or filesystem. By registering this function with register_uninstall_hook(), it ensures that this cleanup logic is executed when the plugin is uninstalled, maintaining the integrity and performance of the WordPress site.

Leave an answer