WordPress Basic Allowed HTML for wp_kses
Here is a function that I use in my plugin, Dashboard Widgets Suite. It provides a sane, practical set of HTML tags and attributes for WP’s wp_kses
family of functions.
About wp_kses()
In WordPress, the wp_kses()
(and related kses functions) sanitizes markup using the following syntax:
<?php wp_kses($string, $allowed_html, $allowed_protocols); ?>
For the second parameter, $allowed_html
, you pass an array of allowed HTML elements.
Safe set of allowed HTML tags & attributes
There are various approaches to providing a suitable $allowed_html
parameter, but the method that I find to be the most sane and flexible is to pass my own custom-built array. To make things easier, I package my set of allowed HTML tags and attributes in the following convenient function:
function shapeSpace_allowed_html() {
$allowed_tags = array(
'a' => array(
'class' => array(),
'href' => array(),
'rel' => array(),
'title' => array(),
),
'abbr' => array(
'title' => array(),
),
'b' => array(),
'blockquote' => array(
'cite' => array(),
),
'cite' => array(
'title' => array(),
),
'code' => array(),
'del' => array(
'datetime' => array(),
'title' => array(),
),
'dd' => array(),
'div' => array(
'class' => array(),
'title' => array(),
'style' => array(),
),
'dl' => array(),
'dt' => array(),
'em' => array(),
'h1' => array(),
'h2' => array(),
'h3' => array(),
'h4' => array(),
'h5' => array(),
'h6' => array(),
'i' => array(),
'img' => array(
'alt' => array(),
'class' => array(),
'height' => array(),
'src' => array(),
'width' => array(),
),
'li' => array(
'class' => array(),
),
'ol' => array(
'class' => array(),
),
'p' => array(
'class' => array(),
),
'q' => array(
'cite' => array(),
'title' => array(),
),
'span' => array(
'class' => array(),
'title' => array(),
'style' => array(),
),
'strike' => array(),
'strong' => array(),
'ul' => array(
'class' => array(),
),
);
return $allowed_tags;
}
The tags and attributes provided by this function may be customized as desired. Here is an example of usage:
$allowed_html = shapeSpace_allowed_html();
$sanitized_string = wp_kses($raw_string, $allowed_html);
For more information, check out the wp_kses()
reference link below.