Problem
By default, WordPress does NOT escape the the_title() function.
The the_title() function outputs the post title in the loop, and is typically used in theme PHP files.
This is not considered a bug – it is a deliberate design choice and is considered a “feature”.
Solution
The two common methods to ensure that the_title() outputs escaped content are:
Solution 1: wrap in esc_html()
Each use of the_title() is wrapped with esc_html()
For example
esc_html( the_title( '<h3>', '</h3>' ) )
Solution 2: Create a helper filter
This will escape all uses of the_title()
function itsg_escape_title( $title ){ return esc_html( $title ); } add_filter( 'the_title', 'itsg_escape_title' );
Other options
Other options include:
htmlspecialchars()
You can use the htmlspecialchars() function to escape HTML entities in the post title.
echo htmlspecialchars(get_the_title());
wp_kses()
The wp_kses() function allows you to specify an allowed list of HTML tags while escaping everything else.
It can be useful if you want to allow certain tags in the post title.
echo wp_kses(get_the_title(), array('strong', 'em'));
Custom function
You can create a custom function that combines the_title() with the necessary escaping functions.
function my_escaped_title() { $title = get_the_title(); $escaped_title = esc_html($title); echo $escaped_title; }
You can then use my_escaped_title()
in your theme files instead of the_title().