Cannot Add Featured Image in WordPress — CSP unsafe-eval Error Explained

Cannot add a featured image in WordPress: CSP unsafe-eval error

If you suddenly can’t set a featured image, select files in the Media Library or pick images in ACF fields, and the browser console shows an error about unsafe-eval, the culprit is a Content Security Policy (CSP) that is too strict for the WordPress admin.

Problem: Clicking “Set featured image” opens the media library, but images can’t be selected. The browser console shows a Content Security Policy error mentioning unsafe-eval.

Recognise the error

Open the browser console (F12 → Console). If the error looks like this, you’re in the right place:

Uncaught EvalError: Refused to evaluate a string as JavaScript because
'unsafe-eval' is not an allowed source of script in the following
Content Security Policy directive: "default-src 'self' 'unsafe-inline' data: …"

Why the media library needs unsafe-eval

The media modal builds its interface from Underscore.js templates (wp.template()). Underscore compiles each template into a JavaScript function with new Function(), which CSP treats the same as eval(). A policy without 'unsafe-eval' blocks it, and the media modal can’t render the items.

Find where the policy comes from

To confirm that a CSP header is sent, inspect the response headers in the browser’s Network tab, or scan the site with securityheaders.com. Then find its source:

  1. The .htaccess file: search for a Header set Content-Security-Policy line.
  2. A security or headers plugin, or the theme: check the plugin settings and search the theme files for header() calls that send a CSP.
  3. The server configuration of your hosting provider: less common, but worth asking support if the first two come up clean.

Fix: relax the policy for the admin only

The safest fix is to keep a strict policy on the front end and send a different one, or none, in wp-admin. If you send the header from PHP, check where the request goes:

add_action( 'send_headers', 'helloadmin_csp_header' );
function helloadmin_csp_header() {
    // Front end only: the admin doesn't get this policy at all.
    // Put your own policy here. Remember that WordPress and plugins print inline scripts.
    $policy = "default-src 'self'; script-src 'self' 'unsafe-inline'; img-src 'self' data:";

    header( 'Content-Security-Policy: ' . $policy );
}

send_headers runs only for front-end requests, not for wp-admin. If the header is set in .htaccess for the whole site, add 'unsafe-eval' to the script-src directive (or to default-src if there is no script-src), or move the header to PHP as above.

NOTE: Adding 'unsafe-eval' relaxes your CSP. If you didn’t set a Content Security Policy on purpose, find out which plugin or configuration added it rather than simply appending permissions you may not need.