Uninstalling a plugin: delete all options with specific prefix

Objective

As all plugin developer, I want to delete all options that begin with the same prefix.

Backstory

I’ve developed a plugin that stores data in the options. When the user uninstalls the plugin, the uninstall.php in the plugin executes the following code:

if ( !defined( 'WP_UNINSTALL_PLUGIN' ) ) {
    exit;
}

delete_option( 'myplugin_some_opt_1' );
delete_option( 'myplugin_some_opt_2' );
delete_option( 'myplugin_some_opt_3' );
delete_option( 'myplugin_some_opt_4' );

Since all of the options start with myplugin_, I want to implement a wildcard. Logicall, I assume that it would look something like this:

if ( !defined( 'WP_UNINSTALL_PLUGIN' ) ) {
    exit;
}

delete_option( 'myplugin_*' );

2 s
2

Replace “myplugin_” with your prefix:

global $wpdb;

$plugin_options = $wpdb->get_results( "SELECT option_name FROM $wpdb->options WHERE option_name LIKE 'myplugin_%'" );

foreach( $plugin_options as $option ) {
    delete_option( $option->option_name );
}

Leave a Comment