Stop Malware Showing in WordPress

I’ve been battling against a particularly nasty and smart piece of malware recently and I don’t mind admitting that I’m a bit tired of it and wish it would bugger off.

During this process, I wanted to stop scripts/malware running in the front-end of WordPress. You’d think that’d be a pretty common thing but I couldn’t find one plugin that would let me do it.

What I wanted was a script to remove any scripts from content before showing it. I also wanted it to email me if it filtered out a script so I would know that the site was infected again and could do something about it. It’s a handy wee function that stops the actual infection from running so that end users don’t see it while at the same time letting you know so you can go fix it up.

Just add this function to your theme’s functions.php and edit it to add your email addresses etc. Just remember that this is just a warning system and to stop a lot of damage, not an actual fix to the malware problem.

function stop_scripts_filter($content){
if(preg_match("/<script.*?\/script>/s", $content)){
$headers[] = ‘Content-Type: text/html; charset=UTF-8’;
$headers[] = ‘From: My Website <>’;
wp_mail("","Script filtered out", "A script has been removed from your site.", $headers, $attachments );
$content = preg_replace("/<script.*?\/script>/s", "", $content);
return $content;

add_filter( ‘the_content’, ‘stop_scripts_filter’ );