Sanitizing comments or escaping comment_text()

I’m creating a template for comments on my WordPress site. I noticed that a simple <script>alert(1);</script> slips through the default WP codex implementation of comments, using the comment_text() function to display my comments. No bueno.

How can i properly sanitize and/or escape WordPress comments? The esc_html() function, seems to do nothing in this case.

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

After thinking about this a little bit, I guess that the proper way to ensure that your comments are properly escaped, is by doing something like this:

$the_comment = get_comment_text();
echo '<p>' . esc_html($the_comment) . '</p>';

Instead of simply using the function like this:

comment_text();

Why even have these handy functions in the first place, if they aren’t properly escaped? The comment_author(); function IS, yet this is not for some reason?

Perhaps I am missing something?

I was missing something: the unfiltered_html capability given to the admin role, extends to comments. Read more here: https://wordpress.org/support/article/roles-and-capabilities/#unfiltered_html


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