Sanitizing user input in WordPress with wp_kses

The WordPress wp_kses function is a useful tool for sanitizing and validating data input. It helps prevent potential security vulnerabilities by stripping out any potentially harmful code, such as JavaScript or HTML tags, from user input. This can be especially important when dealing with user-generated content, such as comments or form submissions, to ensure that the data being stored or displayed on the website is safe and secure.

By using wp_kses, developers can help protect their WordPress websites from cross-site scripting (XSS) attacks and other malicious activities that could compromise the site’s security and integrity.

Parameters Accepted by wp_kses Function

  • $content (string, required): Text content to filter.
  • $allowed_html (array[]string, required): An array of allowed HTML elements and attributes, or a context name such as ‘post’. See wp_kses_allowed_html() for the list of accepted context names.
  • $allowed_protocols (string[], optional, default value: array()): Array of allowed URL protocols. Defaults to the result of wp_allowed_protocols().

Value Returned by wp_kses Function

The function returns a string containing the filtered content containing only the allowed HTML.


How to sanitize a string using wp_kses

$string = "Hello, <script>world</script>!";
$sanitized_string = wp_kses( $string );
echo $sanitized_string;

This code snippet uses the wp_kses function to sanitize the string. This will remove the tags that are not allowed.

How to customize allowed HTML tags and attributes using wp_kses

$string = "Hello, <a href=''>world</a>!";
$allowed_html = array(
 'a' => array(
 'href' => array()
$sanitized_string = wp_kses( $string, $allowed_html );
echo $sanitized_string;

This code snippet uses the wp_kses function to customize the allowed HTML tags and attributes by allowing only the a tag with the href attribute. Any other HTML tags or attributes in the string will be removed.


In conclusion, the wp_kses function is an essential tool for sanitizing and validating input in WordPress. By using this function, developers can protect their websites from malicious attacks and ensure that user-generated content meets the necessary security standards. With its customizable options and thorough documentation, wp_kses is a valuable asset for any WordPress project. By implementing this function in their code, developers can enhance the security and integrity of their websites, providing a safer and more reliable experience for their users.

Related WordPress Functions