Allowing Data Attributes in WordPress Posts


How to prevent the HTML5 data-* attribute being stripped from your WordPress posts.

I’ve been using the Zurb Foundation framework a lot recently and have had lots of fun adapting it to work well with WordPress.

If you’ve used the framework you’ll know how good it is and how it makes much use of the data attribute for hooking scripts and passing arguments.

I’ve been developing a plugin to help myself and others make use of elements from the Foundation framework inside posts. However, users with roles other than admin can’t post unfiltered html and WordPress doesn’t currently recognise the data attribute as an allowed html attribute.

Anytime someone other than an admin makes or edits a post, the important attribute will be stripped out and the world falls apart.

Kses – Removing Evil

WordPress uses a filter called kses which apparently stands for kses strips evil scripts. At any rate it’s pretty cool and you can find it located in wp-includes/kses.php.

The bit we’ll need is right down around line 500 and simply returns an array of allowed terms dependant on the argument provided for $context.

We’ve got a nice handy filter here, wp_kses_allowed_html which we can use to filter the array of html tags and attributes that are allowed depending on the context.

Armed with this I came up with…

So we’re simply checking that the context is not an array. Valid values are post | strip | data | entities or the name of a field filter such as pre_user_description. In this case I want the attribute allowed when posting.

So now we’re free to include whatever tags and attributes we want. It’s worth noting if you take a look at the array towards the beginning of kses.php that the array is structured like so: $allowed['tag']['attribute']. So you can add or remove the same attributes from different tags.

If you’ve got any suggestions for improvements or alternate uses let me know in the comments.

Further Reading

Leave a Reply

Your email address will not be published. Required fields are marked *