How to add nonce tag to inline script for CSP

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.

Topic filters Wordpress

Category Web


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 );

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.