Custom data validation in WordPress is something that many who have built custom solutions for others have likely used.
In fact, anyone who has made a theme or a plugin has probably used some form of data validation even if it’s just escaping some attribute that will be part of the rendered markup.
This is a major step in making sure that anything you’re creating is securely managing information coming from the database.
But whenever you’re working on a custom solution that requires you use various elements and attributes, how can you specify only the supported attributes?
Data Validation in WordPress
WordPress provides a handful of data validation functions that make it straightforward depending on the type of information with which you’re working.
But if you’re, say, dynamically building a list of select
elements and you only want to allow one attribute on the select
element and, say, two elements on the option
elements then you’re likely better off using wp_kses.
This function makes sure that only the allowed HTML element names, attribute names and attribute values plus only sane HTML entities will occur in $string. You have to remove any slashes from PHP’s magic quotes before you call this function
It’s powerful on its own, but it also allows you to set up your set of HTML that’s authorized to pass through the function.
For example, say you’re dynamically building a list of option
elements that will be part of a select
element. You may do something like this:
Without specifying any additional information, You won’t be able to introduce value
attributes or selected
attributes on the option
elements nor will you be able to add a name
attribute on the select
element.
All of the above are important when working with administration pages and saving and setting user selections. To introduce support for the above options, you can define a set of allowed HTML and then pass that into wp_kses
.
And the final piece of code will look something like this:
This is but an example of how to use this. It may be different than what you need, but the purpose is to show how you can introduce HTML that will be considered valid for what you need.
Leave a Reply
You must be logged in to post a comment.