sanitize_text_field( string $str ): string
- Since
- 2.9.0
- Source
wp-includes/formatting.php:5555
Strips tags, invalid UTF-8, line breaks, extra whitespace and percent-encoded characters from a single-line string, returning the cleaned result. Built for short user-supplied fields like a name or subject line rather than multi-line content. It runs through the sanitize_text_field filter before returning, so plugins can alter the result. For fields where line breaks matter, use sanitize_textarea_field instead.
Description
- Checks for invalid UTF-8,
- Converts single
<characters to entities - Strips all tags
- Removes line breaks, tabs, and extra whitespace
- Strips percent-encoded characters
Compatibility
- WordPress
- since 2.9.0
- PHP
- 7.4–8.6-dev
- 6.7.7
- 6.8.8
- 6.9.7
- 7.0.4
- 7.1.0
Present in every tracked release (6.7.7 to 7.1.0), and compiles on PHP 7.4 through 8.6-dev.
Parameters
$strstring- String to sanitize.
Return value
string- Sanitized string.
Code examples
Every example is editable and runs in a real WordPress booted in your browser by WordPress Playground. Press Run, then edit the code: clicking away re-runs it. Nothing is sent anywhere until you do.
Sanitize a text field submitted via $_POST before saving it
A form handler receives a raw customer name with extra whitespace and a stray tag that needs to be stripped before it touches post meta.
$_POST['customer_name'] = " Jane <b>Doe</b>\n\t ";
$clean_name = sanitize_text_field( $_POST['customer_name'] );
update_post_meta( 2, 'customer_name', $clean_name );
printf( 'Stored customer name: %s', esc_html( get_post_meta( 2, 'customer_name', true ) ) );sanitize_text_field only cleans the string; it does not check capabilities or verify a nonce, so a real form handler still needs those checks.
Clean up a comma-separated tag list before assigning it to a post
A raw string typed into a plugin's admin field can carry tabs and line breaks that should collapse before the tags are split apart.
$raw_tags = "news, \tupdates\n, featured";
$clean_tags = sanitize_text_field( $raw_tags );
$tag_names = array_map( 'trim', explode( ',', $clean_tags ) );
wp_set_post_tags( 1, $tag_names, true );
print_r( wp_get_post_tags( 1, array( 'fields' => 'names' ) ) );wp_set_post_tags still needs valid or existing term names; sanitize_text_field only tidies the raw string, it does not validate the terms.
Common problems and fixes · 4
- Why do my line breaks disappear when I sanitize a textarea value with this function?
- Why did part of my string vanish when it contained something like %20 or %3D?
- Is it safe to echo the result of sanitize_text_field() straight into HTML?
- Can a plugin change what sanitize_text_field() returns?
Why do my line breaks disappear when I sanitize a textarea value with this function?
Why did part of my string vanish when it contained something like %20 or %3D?
Is it safe to echo the result of sanitize_text_field() straight into HTML?
Can a plugin change what sanitize_text_field() returns?
Alternatives and related functions
sanitize_textarea_field- When the input is multi-line, such as a comment or message, and line breaks need to survive sanitizing.
wp_strip_all_tags- When all that's needed is tag stripping without the whitespace collapsing and percent-encoding removal sanitize_text_field also performs.
sanitize_title- When the string will be used as a slug or URL segment rather than displayed as plain text.
esc_html- When the goal is safe HTML output rather than cleaning up raw input before storage.
Performance profile
How much work a call to sanitize_text_field() does, and what it touches: the algorithmic scaling, the Zend instruction count per call across PHP versions, the hooks it hands control to, and the core code that calls it. Measured from the compiled opcodes, not a stopwatch, so every number is identical on any machine running the same PHP version, and every function in core is ranked by cost.
- Cost class
- Trivial
- Scaling
- Constant
- Instructions
- 12
- Plugin surface
- 1 hook
- Called by
- 50
Touches nothing outside its own arguments.
No loop in the body: the same number of instructions runs whatever you pass in.
Executed per call on PHP 8.5. The body compiles to 12.
Third-party callbacks on 'sanitize_text_field' run inside this call, and their cost is not bounded by anything here.
50 places in core call this, so the cost is paid more often than your own code shows.
What it touches
- hookthird-party callbacks
apply_filters()called directly
Further down the call graph this can also reach option, cache, serialize, query and transient. Those are the worst case, several calls deep and usually down an error path, not what a normal call pays.
What one call costs · 1 distinct outcome
One number would be a lie: the work depends on which branch runs. These are every distinct cost sanitize_text_field() can have, taken from its control-flow graph on PHP 8.5.
| When | Instructions | Calls it makes |
|---|---|---|
| always | 12 | _sanitize_text_fields(), apply_filters() |
Across PHP versions
Compiles the same on PHP 7.4, 8.1, 8.2, 8.3, 8.4, 8.5 and 8.6-dev: 12 instructions, 12 executed per call, 0 branches. The work does not change between versions.
An instruction is not a fixed amount of time, so a matching count is not necessarily the same speed; what it rules out is a difference in the work itself.
Hooks and filters fired · 1
One hook fires while sanitize_text_field() runs, in this order:
- apply_filters( sanitize_text_field )filterline 5566 (+11 into the body)
Filters a sanitized text field string.
Uses · 2
- _sanitize_text_fields()Internal helper function to sanitize a string from user input or from the database.
- apply_filters()Calls the callback functions that have been added to a filter hook.
Used by · 50
- WP_Application_Passwords::create_new_application_password()Creates a new application password.
- WP_Application_Passwords::update_application_password()Updates an application password.
- WP_Customize_Manager::handle_load_themes_request()Loads themes into the theme browsing/installation UI.
- WP_Customize_Manager::save()Handles customize_save WP Ajax request to save/update a changeset.
- WP_Customize_Nav_Menu_Setting::sanitize()Sanitize an input.
- WP_Customize_Nav_Menus::ajax_search_available_items()Ajax handler for searching available menu items.
- WP_Debug_Data::get_wp_dropins()Gets the WordPress drop-in section of the debug data.
- WP_Debug_Data::get_wp_mu_plugins()Gets the WordPress MU plugins section of the debug data.
- WP_Debug_Data::get_wp_plugins_raw_data()Gets the raw plugin data for the WordPress active and inactive sections of the debug data.
- WP_Debug_Data::get_wp_themes_inactive()Gets the WordPress inactive themes section of the debug data.
- WP_Font_Collection::get_sanitization_schema()Retrieves the font collection sanitization schema.
- WP_Font_Utils::get_font_face_slug()Generates a slug from font face properties, e.g. `open sans;normal;400;100%;U+0-10FFFF`
Show all 50
- WP_Font_Utils::sanitize_font_family()Sanitizes and formats font family names.
- WP_Links_List_Table::prepare_items()
- WP_MS_Themes_List_Table::prepare_items()
- WP_Nav_Menu_Widget::update()Handles updating settings for the current Navigation Menu widget instance.
- WP_Plugin_Install_List_Table::prepare_items()
- WP_Plugins_List_Table::prepare_items()
- WP_Privacy_Requests_Table::get_views()Gets an associative array ( id => link ) with the list of views available on this table.
- WP_Privacy_Requests_Table::prepare_items()Prepares items to output.
- WP_REST_Attachments_Controller::create_item()Creates a single attachment.
- WP_REST_Pattern_Directory_Controller::prepare_item_for_response()Prepare a raw block pattern before it gets output in a REST API response.
- WP_REST_Plugins_Controller::sanitize_plugin_param()Sanitizes the "plugin" parameter to be a proper plugin file with ".php" appended.
- WP_REST_Site_Health_Controller::get_directory_sizes()Gets the current directory sizes for this install.
- WP_REST_Templates_Controller::get_wp_templates_author_text_field()Returns a human readable text for the author of the template.
- WP_Sitemaps::render_sitemaps()Renders sitemap templates based on rewrite rules.
- WP_Theme_Install_List_Table::prepare_items()
- WP_Widget_Archives::update()Handles updating settings for the current Archives widget instance.
- WP_Widget_Calendar::update()Handles updating settings for the current Calendar widget instance.
- WP_Widget_Categories::update()Handles updating settings for the current Categories widget instance.
- WP_Widget_Custom_HTML::update()Handles updating settings for the current Custom HTML widget instance.
- WP_Widget_Meta::update()Handles updating settings for the current Meta widget instance.
- WP_Widget_Pages::update()Handles updating settings for the current Pages widget instance.
- WP_Widget_Recent_Comments::update()Handles updating settings for the current Recent Comments widget instance.
- WP_Widget_Recent_Posts::update()Handles updating the settings for the current Recent Posts widget instance.
- WP_Widget_Search::update()Handles updating settings for the current Search widget instance.
- WP_Widget_Tag_Cloud::update()Handles updating settings for the current Tag Cloud widget instance.
- WP_Widget_Text::update()Handles updating settings for the current Text widget instance.
- _wp_personal_data_handle_actions()Handle list table actions.
- edit_post()Updates an existing post with values provided in `$_POST`.
- edit_user()Edit user settings based on contents of $_POST
- media_handle_upload()Saves a file submitted from a POST request and create an attachment post for it.
- register_new_user()Handles registering a new user.
- rest_sanitize_value_from_schema()Sanitize a value based on a schema.
- validate_another_blog_signup()Validates a new site sign-up for an existing user.
- validate_blog_signup()Validates new site signup.
- wp_ajax_delete_plugin()Handles deleting a plugin via AJAX.
- wp_ajax_health_check_get_sizes()Handles site health check to get directories and database sizes via AJAX.
- wp_ajax_save_attachment()Handles updating attachment attributes via AJAX.
- wp_ajax_toggle_auto_updates()Handles enabling or disable plugin and theme auto-updates via AJAX.
Source code
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 );}Changelog
Introduced in 2.9.0. Unchanged from 6.7.7 through 7.1.0.
Signature, return type and hooks compared across 5 parsed releases.
About this page
- Parsed data
- Generated from the wordpress-develop 6.7.7 tag, from
src/wp-includes/formatting.php, and regenerated for each WordPress release so it tracks the code rather than a snapshot of it. - Corrections
- Something wrong on this page? Report it and it gets fixed in the next regeneration.