Remove All Matching Options from the WordPress Database
Typically when you want to remove an option from the WordPress database, you can use a function like delete_option(). But there are cases where such functions are insufficient. For example, in a previous version of my plugin Blackhole for Bad Bots, a database option is added for each blocked request, and each option name includes a random string, like blackhole_1btvitae9o
. Because of the random string, using a function like delete_option()
is useless. So to provide a solution, this quick post provides two ways to remove all matching options from the WordPress database.
Technique #1
The first way to remove all matching options from the database actually does use delete_option()
, however additional logic is used to determine which options to delete. Here is the code:
// Remove all matching options from the database
foreach (wp_load_alloptions() as $option => $value) {
if (strpos($option, 'blackhole_') !== false) {
delete_option($option);
}
}
The only required modification is to replace blackhole_get_vars
with the option name that you want to delete. For this example, and option name that contains the string blackhole_get_vars
is matched and deleted. So all of these options would be deleted:
blackhole_4qjg68sl5t
blackhole_ole5sq4rin
blackhole_9ogln954hh
blackhole_loskonz0y8
blackhole_nzb0bcl6e7
.
.
.
And so forth. So it’s an effective way to target and remove all options that match a particular pattern. Important: be careful and choose a pattern that ONLY exists in the options you want to remove. Remember to test thoroughly before using this code in a live plugin.
Technique #2
Instead of using delete_option()
, this technique uses the wpdb
Class to directly remove all options that are LIKE the specified pattern.
global $wpdb;
$wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE '%blackhole_%'");
The only required change is to replace blackhole_
with whatever option name you want to find and delete. You have to be careful and choose a pattern that ONLY exists in the options you want to remove. Remember to test thoroughly before using this code in a live plugin.