The register_uninstall_hook() WordPress PHP function sets the uninstallation hook for a plugin.
Usage
register_uninstall_hook( __FILE__, 'my_plugin_uninstall' );
Parameters
$file(string) – Required. The plugin file.$callback(callable) – Required. The callback to run when the hook is called. Must be a static method or function.
More information
See WordPress Developer Resources: register_uninstall_hook()
Examples
Basic Uninstall Hook
Register an uninstall hook when the plugin is activated:
function my_plugin_activate() {
    register_uninstall_hook( __FILE__, 'my_plugin_uninstall' );
}
register_activation_hook( __FILE__, 'my_plugin_activate' );
function my_plugin_uninstall() {
    // Code to perform during uninstallation
}
Delete Options on Uninstall
Delete plugin options when the plugin is uninstalled:
function my_plugin_uninstall() {
    delete_option('my_plugin_option');
}
register_uninstall_hook( __FILE__, 'my_plugin_uninstall' );
Remove Custom Post Type on Uninstall
Remove all posts of a custom post type when the plugin is uninstalled:
function my_plugin_uninstall() {
    $posts = get_posts( array(
        'post_type'   => 'my_custom_post_type',
        'numberposts' => -1,
        'post_status' => 'any'
    ));
    foreach ( $posts as $post ) {
        wp_delete_post( $post->ID, true );
    }
}
register_uninstall_hook( __FILE__, 'my_plugin_uninstall' );
Remove Custom Taxonomy Terms on Uninstall
Remove all terms of a custom taxonomy when the plugin is uninstalled:
function my_plugin_uninstall() {
    $terms = get_terms( array(
        'taxonomy'   => 'my_custom_taxonomy',
        'hide_empty' => false,
    ));
    foreach ( $terms as $term ) {
        wp_delete_term( $term->term_id, 'my_custom_taxonomy' );
    }
}
register_uninstall_hook( __FILE__, 'my_plugin_uninstall' );
Remove Custom Database Table on Uninstall
Drop a custom database table when the plugin is uninstalled:
function my_plugin_uninstall() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'my_custom_table';
    $wpdb->query( "DROP TABLE IF EXISTS {$table_name}" );
}
register_uninstall_hook( __FILE__, 'my_plugin_uninstall' );