Allow HTML in WordPress Category Name/Title

April 17th, 2022

While there is sufficient information online on how to allow HTML in WordPress category descriptions, I have found that there is no decent information on allowing HTML in the name/title of the category. It always gets completely stripped out after saving changes.

Be aware that adding HTML to the category name may have unintended effects for you, such as the code itself appearing in the title of the category page, but there are still some situations where allowing HTML in WordPress category names can be useful.

So I went in to the WP core to find out what’s going on.
We can see that in WP core in wp-includes/default-filters.php there are 3 filters applied to the category name under pre_term_name

// Strip, trim, kses, special chars for string saves.
foreach ( array( 'pre_term_name', 'pre_comment_author_name', 'pre_link_name', 'pre_link_target', 'pre_link_rel', 'pre_user_display_name', 'pre_user_first_name', 'pre_user_last_name', 'pre_user_nickname' ) as $filter ) {
	add_filter( $filter, 'sanitize_text_field' );
	add_filter( $filter, 'wp_filter_kses' );
	add_filter( $filter, '_wp_specialchars', 30 );

So, we want to remove them all to allow HTML in the category name field. Please note that this poses a security risk if you have users who are able to create/edit categories who might not be trustworthy. You should only use the following code in certain circumstances where these issues are not a concern, which will be the case for most readers I imagine.

Place the following code in your theme/child theme’s functions.php or in your custom plugin:

foreach (array('pre_term_name') as $filter) {
    remove_filter($filter, 'sanitize_text_field');
    remove_filter($filter, 'wp_filter_kses');
    remove_filter( $filter, '_wp_specialchars', 30 );

Was this post helpful?