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_html, esc_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.
The wp_kes WordPress function takes in three arguments:
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)) );
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 );