How to protect your WordPress site from problematic code in the_content

By default, WordPress lets you write basically anything in the content of a page, post, or custom post type. When you write or see the_content like this in a WordPress template:

<?php the_content(); ?>

That’s likely allowing any code through. Even content that could be problematic. Problematic code would include raw iframes and JavaScript scripts. For example, let’s say you wrote this in the text tab of the classic editor or in the custom HTML block in Gutenberg.

<script>alert('here');</script>

When you save that post and viewed it, you would see a JavaScript alert pop up that says here. That is an innocuous example that is maybe just annoying. But let’s say some admin or editor credentials are compromised and a hacker writes JavaScript that could exploit the viewer in some way. How can you defend against that? Here is a simple PHP script you can add to your site to remove any scripts or iframes from the content, but will not effect embeds and shortcodes which may have iframes or scripts:

function please_sanitize_the_content( $content ) {
	return wp_kses_post( $content );
}

add_filter( 'the_content', 'please_sanitize_the_content', 1 );

This filter on the_content utilizes the function wp_kses_post which will only allow HTML that WordPress deems safe. We are putting it at priority 1 (that’s what the 1 means in the add_filter function) so it runs really early and doesn’t effect embeds or shortcodes that could have scripts or iframes that your site allows.

In addition you can also include this line if you are using the Advanced Custom Fields plugin:

add_filter( 'acf_the_content', 'please_sanitize_the_content', 1 );

This is a similar filter to the_content but is for Advanced Custom Fields rich editor fields.

Also note… you can also set the disallow unfiltered HTML constant as such in wp-config.php to ensure your content is clear of malicious scripts and iframes.

define( 'DISALLOW_UNFILTERED_HTML', true );

However, this method is not retroactive to content that has already been saved to the database, and it also removes the Additional CSS feature in the customizer (which I don’t love, but find useful at a moment’s notice).

,

Comments

Leave a Reply

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