sanitize_text_field( string $str ): string

Sanitizes a string from user input or from the database.


  • Checks for invalid UTF-8,
  • Converts single < characters to entities
  • Strips all tags
  • Removes line breaks, tabs, and extra whitespace
  • Strips percent-encoded characters

See also


String to sanitize.


string Sanitized string.

More Information

Basic Usage

<?php sanitize_text_field( $str ) ?>


function sanitize_text_field( $str ) {
	$filtered = _sanitize_text_fields( $str, false );

	 * Filters a sanitized text field string.
	 * @since 2.9.0
	 * @param string $filtered The sanitized string.
	 * @param string $str      The string prior to being sanitized.
	return apply_filters( 'sanitize_text_field', $filtered, $str );


apply_filters( ‘sanitize_text_field’, string $filtered, string $str )

Filters a sanitized text field string.



User Contributed Notes

  1. Skip to note 7 content

    Check whether the string is a valid UTF-8 character, and remove all HTML tags.

    $str = "<h2>Title</h2>";
    sanitize_text_field( $str ); // it will return "title" without any HTML tags!
  2. Skip to note 8 content

    I ran across an issue with one of my plugins, as it was going through the initial security review, where I had an array that wasn’t passing a security check. The sanitize_text_field() function only works on a string, not an array’d item.

    I located this nice little tidbit of code to sanitize an array, properly.

     * To ensure arrays are properly sanitized to WordPress Codex standards,
     * they encourage usage of sanitize_text_field(). That only works with a single
     * variable (string). This function allows for a full blown array to get sanitized
     * properly, while sanitizing each individual value in a key -> value pair.
     * Source:
     * Author: Broshi, answered Feb 5 '17 at 9:14
    function wporg_recursive_sanitize_text_field( $array ) {
    	foreach ( $array as $key => &$value ) {
    		if ( is_array( $value ) ) {
    			$value = wporg_recursive_sanitize_text_field( $value );
    		} else {
    			$value = sanitize_text_field( $value );
    	return $array;

    IMHO, this needs to become a core feature of WordPress’ sanitation functions. Lior Broshi is the gentleman that came up with this creative solution (I have obtained his permission to share this).

You must log in before being able to contribute a note or feedback.