Using WordPress ‘delete_user_setting()’ PHP function

The delete_user_setting() WordPress PHP function is used to delete user interface settings. When settings are deleted using this function, they are reset back to their defaults. It’s important to note that this function needs to be run before any output has started, as it uses the setcookie() function. The delete_user_setting() function deletes a setting or an array of settings specified by name.

Usage

Here’s a straightforward example of how you might use the delete_user_setting() function:

delete_user_setting('my_custom_setting');

In this example, a user setting named ‘my_custom_setting’ is being deleted, thus it will be reset to its default value.

Parameters

  • $names (string|array): This is a required parameter that specifies the name or names of the settings to be deleted.

More information

See WordPress Developer Resources: delete_user_setting()
This function is part of the WordPress core and is not deprecated.

Examples

Deleting a Single Setting

This code deletes a single user setting named ‘my_theme_setting’. After running this code, ‘my_theme_setting’ will be reset to its default value.

delete_user_setting('my_theme_setting');

Deleting Multiple Settings

You can also delete multiple settings at once by passing an array of setting names. The following code deletes ‘my_theme_setting’ and ‘my_plugin_setting’:

delete_user_setting(array('my_theme_setting', 'my_plugin_setting'));

Checking if a Setting was Deleted

This code attempts to delete ‘my_theme_setting’ and then checks if it was successfully deleted:

$deleted = delete_user_setting('my_theme_setting');

if ( $deleted ) {
    echo 'The setting was deleted successfully.';
} else {
    echo 'The setting could not be deleted.';
}

Deleting a Setting and Refreshing the Page

This code deletes ‘my_theme_setting’ and then refreshes the page to ensure the setting is reset for the next page load:

delete_user_setting('my_theme_setting');
header("Refresh:0");

Conditionally Deleting a Setting

This code checks if ‘my_theme_setting’ exists and only deletes it if it does:

if ( get_user_setting('my_theme_setting') ) {
    delete_user_setting('my_theme_setting');
}