What’s the best method for emptying an option created with the Settings API?

If you wrote your code correctly, then delete_option would be the correct way. The question isn’t how to clear the option; the question is how to structure your code such that the “option does not exist” case is a valid case.

Think about it. The first time you start this code, that option isn’t going to exist at all, right? Your code should be perfectly capable of handling that case, since it’s the first thing the user is ever going to see.

get_option() accepts a default value if the option does not exist. So use that. If you had an empty array for the default, for example, you’d have code like this:

$options = get_option('whatever',array());

Assuming you’re using the settings API, then you should use the isset function in if statements to account for the missing-field case. Something like this:

if (!isset($options['name'])) {
//... the option isn't set to something 
} else {
//... the option is set to something
}

And handle each case of actual use of the option accordingly.

Leave a Comment