Using WordPress ‘pre_kses’ PHP filter

The ‘pre_kses’ WordPress PHP filter allows you to modify content before it is processed by the wp_kses filter, which sanitizes and filters input HTML tags and attributes according to a whitelist.

Usage

function my_pre_kses( $content, $allowed_html, $allowed_protocols ) {
    return $content;
}
add_filter( 'pre_kses', 'my_pre_kses', 10, 3 );

Parameters

  • $content (string)
    • The content to be filtered through KSES.
  • $allowed_html (array[]|string)
    • An array of allowed HTML elements and attributes, or a context name such as ‘post’.
  • $allowed_protocols (string[])
    • An array of allowed URL protocols.

Examples

Sanitize content to prevent HTML injection attacks

add_filter( 'pre_kses', 'my_pre_kses', 10, 3 );
function wp_pre_kses_less_than( $content ) {
return preg_replace_callback( '%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $content );
}

function wp_pre_kses_less_than_callback( $matches ) {
if ( false === strpos( $matches[0], '>' ) ) {
return esc_html( $matches[0] );
}
return $matches[0];
}

Remove all HTML tags from content:

function my_pre_kses( $content, $allowed_html, $allowed_protocols ) {
return strip_tags( $content );
}
add_filter( 'pre_kses', 'my_pre_kses', 10, 3 );