wp_kses( string $content, array[]|string $allowed_html, string[] $allowed_protocols = array() ): string
- Since
- 1.0.0
- Source
wp-includes/kses.php:747
Removes any HTML tags, attributes, and URL protocols from a string that are not explicitly allowed by the arguments you pass in. The allowed list can be a full array of tag and attribute rules or a shorthand context name such as 'post', and the third argument narrows which URL schemes survive in things like href and src. Reach for wp_kses_post() instead when you just need the standard post-content whitelist, since building the allowed_html array by hand is easy to get subtly wrong.
Description
This function makes sure that only the allowed HTML element names, attribute names, attribute values, and HTML entities will occur in the given text string.
This function expects unslashed data.
Compatibility
- WordPress
- since 1.0.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
$contentstring- Text content to filter.
$allowed_htmlarray[]|string- 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_protocolsstring[]optional- Array of allowed URL protocols.
Defaults to the result of wp_allowed_protocols().Default:array()
Return value
string- Filtered content containing only the allowed HTML.
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 arbitrary HTML input against a custom tag whitelist
Clean up a block of untrusted HTML, such as a bio field from an admin settings page, keeping only a handful of formatting tags.
$dirty_html = '<p onclick="alert(1)">Welcome <strong>friends</strong>, visit <a href="javascript:alert(1)" title="link">this page</a>.</p><script>alert("bad")</script>';
$allowed_html = array(
'p' => array(),
'strong' => array(),
'a' => array(
'href' => true,
'title' => true,
),
);
$clean_html = wp_kses( $dirty_html, $allowed_html );
echo '<pre>' . esc_html( $clean_html ) . '</pre>';The onclick attribute, the script tag, and the javascript: link are all stripped because they are not part of the allowed_html array or the default allowed protocols.
Filter post content with the built-in 'post' context instead of a hand-built array
Take an existing post's content, append some injected markup to simulate an unsanitized edit, and run it through wp_kses using the 'post' context shortcut.
$content = get_post_field( 'post_content', 1 );
$content .= '<script>alert("hacked")</script><img src="x" onerror="alert(1)">';
$filtered_content = wp_kses( $content, 'post' );
echo '<p>Original length: ' . esc_html( strlen( $content ) ) . '</p>';
echo '<p>Filtered length: ' . esc_html( strlen( $filtered_content ) ) . '</p>';
echo '<pre>' . esc_html( $filtered_content ) . '</pre>';Passing 'post' as $allowed_html uses the same rules wp_kses_allowed_html() returns for normal post content, which is usually easier to keep correct than maintaining your own array.
Common problems and fixes · 4
- Why did wp_kses() strip out every single tag from my content?
- Why does my <a> tag survive but its href attribute keeps disappearing?
- Why do quotes and backslashes come out mangled after I run $_POST data through wp_kses()?
- Is it safe to call wp_kses() on every post in a loop on every page load?
Why did wp_kses() strip out every single tag from my content?
Why does my <a> tag survive but its href attribute keeps disappearing?
Why do quotes and backslashes come out mangled after I run $_POST data through wp_kses()?
Is it safe to call wp_kses() on every post in a loop on every page load?
Alternatives and related functions
wp_kses_post- When the content is ordinary post content and you want the same allowed tags and attributes core uses for posts, without building an $allowed_html array yourself.
wp_filter_post_kses- When you need a ready-made callback for a content-filtering hook that applies the 'post' context, rather than calling wp_kses() manually inside your own function.
sanitize_text_field- When the value should contain no HTML at all, such as a plain-text title or slug, rather than a filtered subset of tags.
esc_html- When you are only outputting a value and want it displayed as literal text, not interpreted as markup, rather than letting some tags through.
Performance profile
How much work a call to wp_kses() 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
- 26–29
- Plugin surface
- None
- Called by
- 35
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, depending on the branch taken. The body compiles to 29.
Nothing here hands control to plugin code.
35 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()one call below wp_kses()
What one call costs · 2 distinct outcomes
One number would be a lie: the work depends on which branch runs. These are every distinct cost wp_kses() can have, taken from its control-flow graph on PHP 8.5.
| When | Instructions | Calls it makes |
|---|---|---|
!empty($allowed_protocols) | 26 | wp_kses_no_null(), wp_kses_normalize_entities(), wp_kses_hook(), wp_kses_split() |
empty($allowed_protocols) | 29 | wp_allowed_protocols(), wp_kses_no_null(), wp_kses_normalize_entities(), wp_kses_hook(), wp_kses_split() |
Across PHP versions
Compiles the same on PHP 7.4, 8.1, 8.2, 8.3, 8.4, 8.5 and 8.6-dev: 29 instructions, 26–29 executed per call, 1 branch. 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.
Uses · 5
- wp_allowed_protocols()Retrieves a list of protocols to allow in HTML attributes.
- wp_kses_no_null()Removes any invalid control characters in a text string.
- wp_kses_normalize_entities()Converts and fixes HTML entities.
- wp_kses_hook()You add any KSES hooks here.
- wp_kses_split()Searches for HTML tags, no matter how malformed.
Used by · 35
- Automatic_Upgrader_Skin::feedback()Stores a message about the upgrade.
- TwentyNineteen_Walker_Comment::html5_comment()Outputs a comment in the HTML5 format.
- WP_Customize_Manager::handle_load_themes_request()Loads themes into the theme browsing/installation UI.
- WP_Debug_Data::get_wp_active_theme()Gets the WordPress active theme section of the debug data.
- WP_Debug_Data::get_wp_parent_theme()Gets the WordPress parent theme section of the debug data.
- WP_Debug_Data::get_wp_themes_inactive()Gets the WordPress inactive themes section of the debug data.
- WP_Plugin_Install_List_Table::display_rows()Generates the list table rows.
- WP_Site_Health::get_test_persistent_object_cache()Tests if the site uses persistent object cache and recommends to use it if not.
- WP_Site_Health::get_test_sql_server()Tests if the SQL server is up to date.
- WP_Theme::sanitize_header()Sanitizes a theme header.
- WP_Theme_Install_List_Table::install_theme_info()Prints the info for a theme (to be used in the theme installer modal).
- WP_Theme_Install_List_Table::single_row()Prints a theme from the WordPress.org API.
Show all 35
- Walker_Comment::filter_comment_text()Filters the comment text.
- _get_plugin_data_markup_translate()Sanitizes plugin data, optionally adds markup, optionally translates.
- filter_block_kses_value()Filters and sanitizes a parsed block attribute value to remove non-allowable HTML.
- img_caption_shortcode()Builds the Caption shortcode output.
- install_plugin_information()Displays plugin information in dialog box form.
- render_block_core_comment_author_name()Renders the `core/comment-author-name` block on the server.
- render_block_core_comment_content()Renders the `core/comment-content` block on the server.
- twenty_twenty_one_the_posts_navigation()Print the next and previous posts navigation.
- twentynineteen_entry_footer()Prints HTML with meta information for the categories, tags and comments.
- twentytwenty_edit_post_link()Filters the edit post link to add an icon and use the post meta structure.
- twentytwenty_get_theme_svg()Get information about the SVG icon.
- wp_ajax_query_themes()Handles getting themes from themes_api() via AJAX.
- wp_filter_kses()Sanitize content with allowed HTML KSES rules.
- wp_filter_nohtml_kses()Strips all HTML from a text string.
- wp_filter_oembed_result()Filters the given oEmbed HTML.
- wp_filter_post_kses()Sanitizes content for allowed HTML tags for post content.
- wp_kses_data()Sanitize content with allowed HTML KSES rules.
- wp_kses_post()Sanitizes content for allowed HTML tags for post content.
- wp_kses_split2()Callback for `wp_kses_split()` for fixing malformed HTML tags.
- wp_plugin_update_row()Displays update information for a plugin.
- wp_privacy_generate_personal_data_export_group_html()Generate a single group for the personal data export report.
- wp_sidebar_description()Retrieves description for a sidebar.
- wp_trigger_error()Generates a user-level error/warning/notice/deprecation message.
Source code
function wp_kses( $content, $allowed_html, $allowed_protocols = array() ) { if ( empty( $allowed_protocols ) ) { $allowed_protocols = wp_allowed_protocols(); } $content = wp_kses_no_null( $content, array( 'slash_zero' => 'keep' ) ); $content = wp_kses_normalize_entities( $content ); $content = wp_kses_hook( $content, $allowed_html, $allowed_protocols ); return wp_kses_split( $content, $allowed_html, $allowed_protocols );}Changelog
Introduced in 1.0.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.8.8 tag, from
src/wp-includes/kses.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.