0

Is it possible to add nonce tag to inline scripts for wordpress sites using ? I have used a filter script_loader_tag + function for adding tags before but it adds nonce tag only to with src tag. Unfortunately I cant add nonce tag to inline javascript automatically :( So I need a script for some filter which would add nonce tag automatically to tag.

4
  • Can you elaborate what you mean? Do you want a nonce value available as a JS variable? Jun 2, 2022 at 8:38
  • Its easy I want only one thing. Add nonce tag to inline script. Example I want have inline script <script>some script</script> and I want to add nonce tag for CSP ( Content Security Policy ) to script tag like this: <script nonce="somevalue">
    – Macsurf
    Jun 3, 2022 at 18:45
  • 2
    WordPress has a surprising amount of inline scripts and styles. I've tried to get a CSP (Content Security Policy) ready for a WP site and have been stymied. Here's the Trac ticket I opened on the topic a couple versions ago.
    – Pat J
    Jun 3, 2022 at 19:11
  • @Macsurf As from the trac ticket @Pat J created, you can use the script_loader_tag filter for the time being. If the question is reopened I'll post an answer. Jun 3, 2022 at 23:07

1 Answer 1

1

You can use the script_loader_tag filter:

function wpse_406351_script_tag_nonce( $tag, $handle ) {
    if ( $handle === 'id_of_script' /* handle used in wp_enqueue_script/wp_register_script */ ) {
        $nonce = wp_create_nonce(); // Or whatever your nonce value should be

        $tag = str_replace( '<script ', "<script nonce='$nonce' ", $tag );
    }

    return $tag;
}

add_filter( 'script_loader_tag', 'wpse_406351_script_tag_nonce', 10, 2 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.