phpwordpresswildcardprefix

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.

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:


Solution

  • 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.