How Do I Add Content-Security-Policy in WordPress?

Content Security Policy (CSP) is a security measure enforced in web browsers by the Content Security Policy HTTP header. It allows web pages to declare which resources are allowed to load and how they should be loaded.

In WordPress, you can add CSP to your theme or plugin using the wp_add_inline_script() function. This function takes three parameters: the script to be loaded, the domain to which the script is to be loaded from, and the policy to be used.

Let’s look at an example. Suppose you have a plugin called My Plugin that contains a function called my_plugin_function() .

You could add the following line to your plugin’s wp-config.php file to enable CSP:.

define( ‘WP_CONTENT_SECURITY’, true );

Now, when My Plugin is loaded from the WP_CONTENT_SECURITY domain, the my_plugin_function() function will be allowed to run with the following policy:

script-src ‘self’ https://myplugin.com https://myplugin.com/wp-content/themes/mytheme/

Note: If your plugin uses custom scripts or includes any third-party scripts, you’ll need to add these scripts to the whitelist as well.

Now that CSP is enabled, you’ll need to add a policy to your my_plugin_function() function to specify which resources it can load. In this example, we’ll use the same policy as above, which allows scripts from the self and myplugin.

com domains to be loaded.

If you want to allow more resources, you can add a comma-separated list of domains like this:

script-src ‘self’ https://myplugin.com, https://myplugin.com/wp-content/themes/mytheme/

You can also use the same policy for all resources in your plugin, or you can create a custom policy specific to your plugin.

Finally, you’ll need to add the header to your website:

Content-Security-Policy: https://myplugin.com/wp-content/themes/mytheme/my_plugin_function.policy

Now that CSP is enabled and a policy has been specified, any requests for scripts from the myplugin.com domain or resources from the myplugin.

com/wp-content/themes/mytheme folder will be allowed, but requests for scripts from other domains will be denied.

In conclusion, adding Content Security Policy in WordPress is simple and can be done using the wp_add_inline_script() function. Once enabled, you’ll need to add a policy and specify which domains the script can be loaded from.