Hack: Filter Comments That Use All Caps

There’s always that one person that feels the need to YELL by posting comments in all caps. You may just want to delete those comments. But sometimes people who aren’t so Internet-savvy will post in all caps by mistake, or without realizing that it is “yelling.”

I’ve seen hacks where comments like these are converted to lower case characters at the time when the comment is displayed. I don’t like that because it means that processing has to go on for that comment every time it is displayed, forever.

Here’s a simple hack you can put in your functions.php file or your own plugin that will filter the text when the user posts the comment. It looks at how many characters in the comment are upper case, and will only make the change when more than 50 percent are caps. This way, someone can yell just one word, or post acronyms and such without a problem.

function wpfilter_stop_yelling($data) {
	$content = $data['comment_content'];
	preg_match_all("/[A-Z]/", $content, $caps); 
	if (count($caps[0]) / strlen($content) > 0.5) {
		$data['comment_content'] = strtolower($data['comment_content']);
	return $data;

This is a pretty simple function that just uses strtolower to make everything lower case. You could go nuts with lots of code to do things like make the first character of each sentence upper case, etc. But at least with this you get all lower instead of all upper — a big improvement.

This function can be modified for a lot of things. The comment text comes though, you change it, and then pass it on. So you can use a bunch of str_replace calls to sanitize your comments. Like if it drives you crazy that people type iphone instead of iPhone or WordPress instead of WordPress. Things like that.

Leave a Reply

Your email address will not be published. Required fields are marked *