How to Remove HTML Tags from Comments in WordPress

WPTurbo » Snippets » How to Remove HTML Tags from Comments in WordPress
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

While comments on WordPress websites are a great way to engage with your readers and foster a sense of community, they can also be a breeding ground for spam and unwanted HTML code. If you’re looking to clean up your comments section and remove any HTML that may be causing issues or posing a security risk, you’ll need to implement some code changes. In this article, we’ll show you how to remove HTML in comments on your WordPress website.

					function wpturbo_remove_html_from_comments( $comment_text ) {
    $comment_text = strip_tags( $comment_text );
    return $comment_text;
}
add_filter( 'pre_comment_content', 'wpturbo_remove_html_from_comments' );
				

The code snippet above shows how to remove HTML from comments in WordPress. This is done by creating a new function called wpturbo_remove_html_from_comments that takes a single parameter $comment_text which contains the content that the user submitted as their comment.

The strip_tags function is used to remove any HTML tags from the $comment_text variable. This ensures that any HTML code entered by a user cannot affect the display of the comment or website. The strip_tags function is a built-in PHP function that removes HTML and PHP tags from a string.

After cleaning the $comment_text variable, we return it so that WordPress can save the filtered content on the database.

Finally, we hook our wpturbo_remove_html_from_comments function to the pre_comment_content filter using the add_filter function. This filter is executed just before saving comments to the database, allowing our function to filter out any HTML content in the comment.

By adding this code to your theme’s functions.php file, you can ensure that your website only displays clean and properly formatted comments without any potentially harmful HTML code.

Register an account to save your snippets or go Pro to get more features.