Skip to content →

Validating WordPress Settings

A couple days ago, a question regarding WordPress Settings came up at Advanced WordPress Facebook group. Namely, how to limit the number of characters in WordPress blog title.

A couple of nasty jQuery based JavaScript solutions were offered, but that is not the WordPress way of doing things. And such validation should not be done on the client side anyway. So I started looking for an apropriate filter.

And, quite sumarily found one in the update_option function. Just before option value is saved, a general pre_update_option and a more specific pre_update_option_{$option_name} filters are executed. You can check the new value against any clause you need and either pass it through, or throw an error and come back to the Settings screen. So the snippet below will do the trick of limiting the possible length of Blog Title to 40 symbols.

It is a pretty simple and straigthforward piece of code. It hooks in to the update process of a specific option (pre_update_option_blogname), checks for the lenght of the value and, if the value is too long, throws an error in the settings page via add_settings_error() function. The only hacky part comes at line 14, where we overwrite the new $value with the old $old_value. This short-circuits the update_option() function and prevents new (invalid) value to be written into the database. Unfortunately, that also means we lose the value our user just entered and can not show it on the Settings page for the user to modify.

The snippet above is pretty flexible, it can be updated to validate pretty much anything on WP Admin’s Settings pages, if it is stored via Options API. Just replace blogname with name of option in question. Validation logic also can be customized freely – you can check for specific values, validate against other data in the database, etc. – whatever is needed.

The code can be used both in functions.php and in plugins, but I’d recomend the later one, as such things don’t have much to do with presentation, and I prefer keeping non-presentational things away from the theme folder.

P.S. The snippet also contains one translateable string, be sure to update the text-domain accordingly.

Don’t forget to share this via , , Google+, LinkedIn and Reddit.


Published in Code