Plugin Downgrade Script

We recently had a cause to write a script in the event a customer wants to downgrade a plugin. A downgrade is when the manually uploaded plugin has a lower version number than the existing plugin. WordPress recognizes this possibility and helpfully flags the ‘update’ as a ‘downgrade’. Although this is admittedly a rare occurrence, it can happen and should be handled intelligently if there might be a conflict. In our case, a downgrade would cause an issue if the version number was less than 3.0. Here is the code. Place it in your plugin (adding a class and namespace if that is needed).

/**
* If downgrading plugin, delete option
* @param object $upgrader Plugin_Upgrader
*/
function az_plugin_downgrade($upgrader) {

    if ($upgrader->result['destination_name'] == 'my-plugin-slug' && 'downgrade-plugin' === $upgrader->skin->overwrite) {
        $version = $upgrader->new_plugin_data['Version'];
        if ($version < '3') { // change this to whatever condition alerts you to a problem
            // This is a downgrade and an option needs to be deleted
            delete_option('option_to_delete');
        }
    }
}

add_action('upgrader_process_complete', 'az_plugin_downgrade');