X

How to Automatically Replace Swear Words in WordPress Comments

Snippets by IsItWP

Want to replace or remove offensive words in your WordPress comments? With our snippet, you can remove swear words or even affiliate links within your WordPress comments. However, keep in mind that the filtered content will be saved in WordPress.

Instructions:

All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:

add_filter( 'pre_comment_content', 'wps_filter_comment' );
function wps_filter_comment($comment) {
	$replace = array(
		// 'WORD TO REPLACE' => 'REPLACE WORD WITH THIS'
		'foobar' => '*****',
		'hate' => 'love',
		'zoom' => '<a href="http://zoom.com">zoom</a>'
	);
	$comment = str_replace(array_keys($replace), $replace, $comment);
	return $comment;
}

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: Best WordPress Page Builders (Compared).

Comments   Leave a Reply

  1. Instead of replacing words, is there a filter to add the words in the functions.php instead of in the wp-admin > discussion > Blacklist. Sure I can add it inside wp-admin but i’d like to just add it to the functions file.

    1. This method would be for the functions.php file.

  2. Cihan Küsmez July 27, 2013 at 5:24 pm

    what happen if this keywords inside an img tag. I tried and it caused a problem. We can’t see images. My suggestion is it must be a filter that word must not inside a “img” and “a” tag. How can we check ?

  3. good topic

  4. function cudjex($text){$text = str_replace(‘sex’, ‘***’, $text);
    $text = str_replace(‘porno’, ‘***’, $text);
    $text = str_replace(‘cam?? ölüsü seni’, ‘***’, $text);
    $text = str_replace(‘aq’, ‘***’, $text);
    $text = str_replace(‘amk’, ‘***’, $text);
     
    return $text;
    }
    add_filter(‘comment_text’, ‘cudjex’);the simple and useful 🙂

    1. no problem glad that I could help

  5. Make a tutorial teaching on the side to replace words.

    1. Hi Iago,
      Thanks for the feedback at this point the site is primarily for snippets that I find online or create for projects I’m working on. However Ill look at adding some tutorials in the future. Hope you like the snippets!

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!