How to escape content with tag exceptions in WordPress

This article shows you how to escape content with tag exceptions in WordPress.

I was recently trying to write some code to escape all content in a string except image tags within WordPress. Usually to escape content you would use a function like esc_htmlesc_attr or another function more specific to the content type, but I wasn't familiar with how to do this with exceptions, and the previously mentioned functions don't take any additional arguments to facilitate this. 

After a little bit of digging I eventually found wp_kes and wp_kes_post, which were exactly what I needed.

wp_kes function

The wp_kes WordPress function takes in three arguments:

  • The string to escape
  • An array of exceptions (formatted a specific way)
  • An array of protocols that are trusted (optional)

The second array requires you to provide an array of the exceptions tags, with a sub-array of each of the attributes that will be allowed.

Here is a code example for escaping everything except image tags, and allow for the image tags to have the attributes 'src', 'alt', 'width', 'height' and 'class'.

echo wp_kses( $unescaped_content, array('img' => array('src'=>true,'alt'=>true,'width'=>true,'height'=>true,'class'=>true)) );

wp_kes_post

If you're not too picky about which HTML attributes are used but just want to ensure any untrusted elements aren't used then you can alternatively use the wp_kes_post function. It essentially strips anything you wouldn't normally find in post content within WordPress. This function requires only the content parameter:

echo wp_kses_post( $unescaped_content );
Sign Up

NEXT: Strip images from the_content function in WordPress

This post looks at the options for removing images from post content.

comments powered by Disqus
Sign Up

Popular Tags

350x250

Need a web developer?

If you'd like to work with code synthesis on your next project get in touch via the contact page.