Adding HTML Attribute Exceptions to WordPress KSES

UPDATED: June 14, 2013

Okay, so I’ve updated this post to something that actually works and with a real example.

What is KSES?

The wp_kses function sanitizes text, basically checking for valid, allowed HTML and stripping everything else out.

For the full list of allowed HTML, see the kses.php file in the core.

Adding an Attribute to the Allowed List

While the process sounds simple, it took me quite a while to figure it out. Maybe I just don’t work with WordPress and PHP often enough, but I had to refer to at least 5 different websites to put it all together.

While WordPress has a pre_kses hook, so some suggest using that hook with the add_filter function, I broke a couple of plugins when I did that. Instead, I used the add_action function.

You can use a function to either add new HTML elements or specific attributes to existing ones. To allow the data attribute to links, this is the code I used:

[code language=”php”]
function allow_data_event_content() {
global $allowedposttags, $allowedtags;
$newattribute = "data-event";

$allowedposttags["a"][$newattribute] = true;
$allowedtags["a"][$newattribute] = true;
}
add_action( ‘init’, ‘allow_data_event_content’ );
[/code]

The array structure is fairly simple, and best to copy from an example from the kses file and edit as necessary. The WordPress Quick Tips site also has an example.

allowedtags vs. allowedposttags

The difference between allowedtags and allowedposttags is unclear to me, but for me at least, both were necessary, one for editing content (posttags), the other for theme options.

Visual Editor

Since mine doesn’t make any difference in the visual editor, I didn’t have any issues with things not displaying, but if you do, take a look at the suggestion from VIP WordPress.