A Full WordPress Plugin Example — Part 7 Uninstall

When a plugin is uninstalled, you may want to do some clean-up, such as options and settings specific to the plugin and some tables and entries in the database.

There are two methods to do these work:

  • Mehod 1: use the register_uninstall_hook() function.
  • Method 2: use an uninstall.php file in the root folder of the plugin. This magic file is run automatically when the users deletes the plugin.

Here we use the second method.

Create uninstall.php file

Create an uninstall.php inside the root folder of GCMovie plugin.

In the file, we do two things, delete option and clean posts on demand.

In part 5, we add an option that the user can set whether to delete all the movie posts on uninstall. Here we check this option and if it is set to yes, we do the clean job.

<?php
if( ! defined( 'WP_UNINSTALL_PLUGIN' ) || ! WP_UNINSTALL_PLUGIN ) {
    exit;
}

global $wpdb;

// delete options

$options = get_option( 'gcmovie_options' );
delete_option( 'gcmovie_options' );

if ( isset( $options['delete_movies_after_uninstall'] && $options['delete_movies_after_uninstall'] === '1' ) ) {

    // delete posts

    $args = array(
        'post_type' => 'gcmovie'
    );

    $query = new WP_Query( $args );
    while ( $query->have_posts() ) {
        $query->the_post();
        if ( get_post_type() === 'gcmovie' ) {
            $post_id = get_the_ID();
            wp_delete_post( $post_id, true );
        }
    }
    wp_reset_postdata();
}

Resources