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:

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' );

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.

Author: Cynthia

Technologist, Librarian, Metadata and Technical Services expert, Educator, Mentor, Web Developer, UXer, Accessibility Advocate, Documentarian

2 thoughts on “Adding HTML Attribute Exceptions to WordPress KSES”

Leave a Comment

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: