Occasionally, I’ll get questions via Twitter or email from those who are working with the Settings API and aren’t sure why certain values are saving when they shouldn’t actually be saving.

For example, say you have an input field that’s asking for, say, a company’s name. You obviously want to sanitize the data to make sure that it doesn’t have any malicious characters and you want to make sure it’s empty, but what if you’re code is structured in a way that is stores an empty string in the value of the array if it’s not set?

I mean, an empty string is not nothing, right?

Empty Values and the Settings API

So, when working with the Settings API, the sanitization function receives a collection of data that contains the input that you’re ultimately going to save to the database (or reject from saving to the database).

The function gives you the opportunity to work with the data before saving it. That is, this is where you strip out any malicious characters, format the input how you want so that it appears the way you need when retrieving the information, and then return it to be written to the database.

Data Validation

Let’s say that you’re trying to save a company’s name into the database. This means that you likely have an input element that accepts text from the user but you don’t want it to include certain types of characters.

So when it comes to validating the input, it’s not at all uncommon to see something like this:

Assume, from the code above, that there’s a validation class that’s responsible for cleaning up some of the text but notice that in the ternary operator, the result of the false case is an empty string.

And remember that an empty string is not nothing so when you go to return the $new_input collection, you’re actually returning the collection that has an empty string as it’s value.

So how do you fix this? There’s a number of ways you could go about doing this but one of the ways that I’ve found use is to evaluate whether or not the index of the array is empty and, if so, return false; otherwise, return the $new_input collection.

And if false is returned, then WordPress will not save the data to the database.