The delete_option() WordPress PHP function is used to remove an option by its name. This function helps to prevent the removal of protected WordPress options.
Usage
Here’s how to use delete_option():
delete_option('your_option_name');
In this case, ‘your_option_name’ is the name of the option you want to delete.
Parameters
- $option (string) (Required) – Name of the option to delete. This name should not be SQL-escaped.
More information
See WordPress Developer Resources: delete_option()
Please note that this function is a part of WordPress core and isn’t depreciated. You can find the source code in the wp-includes/option.php file.
Examples
Deleting a Single Option
Say you have an option called ‘my_option’ in your options table, and you want to delete it. The code would look like this:
delete_option('my_option');
This code tells WordPress to delete the ‘my_option’ from the options table within your MySQL database.
Removing Multiple Options
If you want to delete multiple options at once, such as when deactivating a plugin, you can use the following code:
$settingOptions = array('plugin_status', 'export_status', 'notifications', 'label_settings'); foreach ($settingOptions as $settingName) { delete_option($settingName); }
In this example, we first define an array of the options we want to delete. We then loop through each of these options, calling the delete_option() function on each one.
Deleting a Theme Option
If you want to remove a theme option, you can do so with the following code:
delete_option('theme_mods_twentytwenty');
This will delete the ‘theme_mods_twentytwenty’ option, which is used by the Twenty Twenty theme to store theme modifications.
Removing a Transient Option
Transient options are temporary options that are automatically deleted after a certain period of time. Here’s how you can manually delete a transient option:
delete_option('_transient_timeout_theme_mods_twentytwenty');
This will delete the timeout for the ‘theme_mods_twentytwenty’ transient option.
Deleting an Option on Plugin Deactivation
You can delete an option when a plugin is deactivated by using the following code in your plugin file:
register_deactivation_hook(__FILE__, 'remove_my_option'); function remove_my_option() { delete_option('my_plugin_option'); }
This will remove the ‘my_plugin_option’ option from the database when the plugin is deactivated. The register_deactivation_hook() function is used to call the remove_my_option() function when the plugin is deactivated.