Should I escape wordpress functions like the_title, the_excerpt, the_content

I had look at the code but I couldnt see any escaping on funcions like the_title the_content the_excerptetc. I might not be reading it right. Do I need to escape these functions in theme development like:

esc_html ( the_title () )

Edit: as pointed out in the answers below the above code is wrong regardless – the code should have read
esc_html ( get_the_title () )

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Escaping depends entirely on the context in which you are using the functions. What is safe for displaying inside <h1> tags, is not necessarily safe to display for the value attribute of an input field, and even that wouldn’t necessarily be safe as a href attribute value….

In short – perform the sanitisation yourself as you output it. Though in the case of the_title () or get_the_title (), esc_html is not necessary, since WordPress applies the following functions:

Note: the_title prints the title – so esc_html ( the_title () ) won’t work. Similarly, the_content prints the content (in any case, you’d expect the content to display HTML).

Method 2

Yes and no – depends on whether you want html in those functions to be output or not. If you escape the_content(), for example, and it contains a <div> tag, that tag would actually be output to the page as &lt;div&gt; instead.

By the way, if you do escape the output of those functions, you’ll want to use their “get_” equivalents (ex. get_the_content()) as those functions echo their output directly.

Method 3

You can simply write a function like this and hook it to the_title filter:

function my_escape_title( $title ){
    return esc_html( $title );
}
add_filter( 'the_title', 'my_escape_title' );


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x