WordPress delete_option(); Wildcard capability?

How would one go about deleting all option names in a WordPress database beginning with a specific prefix?

I would assume we need to specify a prefix, get all options that begin with that prefix, and then delete each option found.

Read More

Here is a sample of the prefix and WP functions for getting and deleting options in the database.

<?php
$prefix = 'cpt_';
$getOpt = get_option($prefix);
foreach($getOpt as $toDelete){
    $deleteOpt = delete_option($prefix);
    if(!$deleteOpt){
        echo 'Failure.';
    }
    if($deleteOpt){
        echo 'Success.';
    }
}
?>

Resources:

Related posts

Leave a Reply

2 comments

  1. You could run this query:

    global $wpdb;
    $wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE 'cpt_%'" );
    

    or put it in a function like so:

    function delete_options_prefixed( $prefix ) {
        global $wpdb;
        $wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '{$prefix}%'" );
    }
    delete_options_prefixed( 'cpt_' );
    
  2. You need to make a “whitelist” of all the variables your plugin sets (I assume you are looking at a plugin uninstall script), then just loop through it at the other end so you can delete them all.

    Something as simple as:

    // Somewhere in your plugin, maybe as a class property
    $pluginDefinedOptions = array('my_name', 'my_created', 'my_modified'); // etc
    
    // Clear up our settings
    foreach($pluginDefinedOptions as $optionName) {
        delete_option($optionName);
    }
    

    This is the only way to keep your plugin code tidy.