WordPress.org

Ready to get started?Download WordPress

Codex

Function Reference/register uninstall hook

Contents

Description

Sets the uninstallation hook for a plugin. Available since WordPress 2.7.

Registers the uninstall hook that will be called when the user clicks on the uninstall link that calls for the plugin to uninstall itself. The link won't be active unless the plugin hooks into the action.

The plugin should not run arbitrary code outside of functions, when registering the uninstall hook. In order to run using the hook, the plugin will have to be included, which means that any code laying outside of a function will be run during the uninstall process. The plugin should not hinder the uninstall process.

If the plugin can not be written without running code within the plugin, then the plugin should create a file named 'uninstall.php' in the base plugin folder. This file will be called, if it exists, during the uninstall process bypassing the uninstall hook.

When using 'uninstall.php' the plugin should always check for the WP_UNINSTALL_PLUGIN constant, before executing. The WP_UNINSTALL_PLUGIN constant is defined by WordPress at runtime during a plugin uninstall, it will not be present if 'uninstall.php' is requested directly. It will also not be present when using the uninstall hook technique. WP_UNINSTALL_PLUGIN is only defined when a uninstall.php file is found in the plugin folder.

Usage

<?php register_uninstall_hook($file$callback?>

uninstall.php

//if uninstall not called from WordPress exit
if ( !defined( 'WP_UNINSTALL_PLUGIN' ) ) 
    exit();

$option_name = 'plugin_option_name';

// For Single site
if ( !is_multisite() ) 
{
    delete_option( $option_name );
} 
// For Multisite
else 
{
    // For regular options.
    global $wpdb;
    $blog_ids = $wpdb->get_col( "SELECT blog_id FROM $wpdb->blogs" );
    $original_blog_id = get_current_blog_id();
    foreach ( $blog_ids as $blog_id ) 
    {
        switch_to_blog( $blog_id );
        delete_option( $option_name );  
    }
    switch_to_blog( $original_blog_id );

    // For site options.
    delete_site_option( $option_name );  
}

Parameters

$file
(string) (required) The PHP file that the callback is located within.
Default: None
$callback
(callback) (required) The callback to run when the hook is called.
Default: None

Notes

Emphasis is put on using the 'uninstall.php' way of uninstalling the plugin rather than register_uninstall_hook.

Discussions

Related

See also index of Function Reference and index of Template Tags.