Allow Specific HTML Tags with wp_kses()

Recently, I was working on a UI for a project at work and needed a way to specify what HTML could be run though a WordPress filter. We had been displaying meta keys and values inside text inputs and now we wanted to also allow text areas since they’re better for working with larger data types like JSON.

We could have simply hard coded detection for JSON and displayed the value inside a text area but we wanted to allow more flexibility than that. So we decided to go with a WordPress filter here so other developers could customize this to fit their needs.

Whenever we return data from a filter, we want to secure (escape) the output to prevent security vulnerabilities. The catch is, doing so will remove the input and text area tags which isn’t what we want. These fields are part of a form and we want to preserve the necessary HTML so that the form will still work.

WordPress has a function we can use called wp_kses() that allows us to specify the tags that area allowed through the filter. In this case, we only want to allow input and textarea. The way to do this is to create an array of the tags you want to allow. You can also pass an array with each of these to specify the attributes allowed for each tag. This array of allowed tags is then passed to the wp_kses()filter as the second argument. Here’s an example:

$allowed_tags         = array(
	'input'    => array(
		'value'    => array(),
		'class'    => array(),
		'type'     => array(),
		'disabled' => array(),
	'textarea' => array(
		'class'    => array(),
		'readonly' => array(),
		'rows'     => array(),

Now this is passed into wp_kses() like this:

wp_kses( apply_filters( 'your_filter', $default ), $allowed_tags );

In this case, that will allow inputs and text areas to be used in the output from our filter. Any other tags like <script>, <div>, <strong> or whatever else will be removed.

So now you can customize the HTML tags allowed through your WordPress filter while escaping the output with wp_kses(). If you have any questions, let us know in the comments.

Leave a Reply

%d bloggers like this: