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.
1 Answer
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 );
script_loader_tag
filter for the time being. If the question is reopened I'll post an answer.