wp_get_inline_script_tag( string $data,  $attributes = array() ): string

Constructs an inline script tag.

Description

It is possible to inject attributes in the <script> tag via the ‘wp_inline_script_attributes’ filter.

If the $data is unsafe to embed in a <script> tag, an empty script tag with the provided attributes will be returned. JavaScript and JSON contents can be escaped, so this is only likely to be a problem with unusual content types.

Example:

// The dangerous JavaScript in this example will be safely escaped.
// A string with the script tag and the desired contents will be returned.
wp_get_inline_script_tag( 'console.log( "</script>" );' );

// This data is unsafe and `text/plain` cannot be escaped.
// The following will return `""` to indicate failure:
wp_get_inline_script_tag( '</script>', array( 'type' => 'text/plain' ) );

Parameters

$datastringrequired
Data for script tag: JavaScript, importmap, speculationrules, etc.
string|bool> $attributes Optional. Key-value pairs representing <script> tag attributes.

Return

string HTML script tag containing the provided $data or the empty string "" if the data cannot be safely embedded in a script tag.

Source

function wp_get_inline_script_tag( $data, $attributes = array() ) {
	$data = "\n" . trim( $data, "\n\r " ) . "\n";

	/**
	 * Filters attributes to be added to a script tag.
	 *
	 * @since 5.7.0
	 *
	 * @param array<string, string|bool> $attributes Key-value pairs representing `<script>` tag attributes.
	 *                                               Only the attribute name is added to the `<script>` tag for
	 *                                               entries with a boolean value, and that are true.
	 * @param string                     $data       Inline data.
	 */
	$attributes = apply_filters( 'wp_inline_script_attributes', $attributes, $data );

	$processor = new WP_HTML_Tag_Processor( '<script></script>' );
	$processor->next_tag();
	foreach ( $attributes as $name => $value ) {
		/*
		 * Lexical variations of an attribute name may represent the
		 * same attribute in HTML, therefore it’s possible that the
		 * input array might contain duplicate attributes even though
		 * it’s keyed on their name. Calling code should rewrite an
		 * attribute’s value rather than sending a duplicate attribute.
		 *
		 * Example:
		 *
		 *     array( 'id' => 'main', 'ID' => 'nav' )
		 *
		 * In this example, there are two keys both describing the `id`
		 * attribute. PHP array iteration is in key-insertion order so
		 * the 'id' value will be set in the SCRIPT tag.
		 */
		if ( null !== $processor->get_attribute( $name ) ) {
			continue;
		}

		$processor->set_attribute( $name, $value ?? true );
	}

	if ( ! $processor->set_modifiable_text( $data ) ) {
		_doing_it_wrong(
			__FUNCTION__,
			__( 'Unable to set inline script data.' ),
			'7.0.0'
		);
		return '';
	}

	return "{$processor->get_updated_html()}\n";
}

Hooks

apply_filters( ‘wp_inline_script_attributes’, array<string, , string $data )

Filters attributes to be added to a script tag.

Changelog

VersionDescription
7.0.0Returns an empty string if the data cannot be safely embedded in a script tag.
5.7.0Introduced.

User Contributed Notes

  1. Skip to note 3 content

    A nice way to include Google Analytics and other scripts in the <head> of the document:

    function wpdocs_add_scripts_head() {
    		// Google Analytics
    		$ga_script = "window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;ga('create', 'UA-XXXXX-Y', 'auto');ga('send', 'pageview');";
    		echo wp_get_inline_script_tag( $ga_script );
    		echo wp_get_script_tag( array(
    			'async' => true,
    			'src' => 'https://www.google-analytics.com/analytics.js'
    		) );
    	}
    	add_action( 'wp_head', 'wpdocs_add_scripts_head', 1 );

    Will output:

    <script>
    window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;ga(‘create’, ‘UA-XXXXX-Y’, ‘auto’);ga(‘send’, ‘pageview’);
    </script>
    <script async src="https://www.google-analytics.com/analytics.js"></script>%5B/php%5D

    This article has good examples https://make.wordpress.org/core/2021/02/23/introducing-script-attributes-related-functions-in-wordpress-5-7/

  2. Skip to note 4 content
    Anonymous User

    This has to be used to make WP a CSP compliant system (at least, in the front end. Remains to be tested in the admin area)

    function wpdocs_add_nonce_to_scripts( $attr ) {
    	if ( 'text/javascript' !== $attr['type'] ) {
    		return $attr;
    	}
    
    	return array(
    		'type' => 'text/javascript',
    		'nonce' => '123',// Your Nonce. Obviously more featured than this example.
    	);
    }
    add_filter( 'wp_inline_script_attributes', 'wpdocs_add_nonce_to_scripts' );

    Then, you can use 'nonce-123' in your CSP Policy, example:
    "script-src 'self' 'noncoe-123';"

You must log in before being able to contribute a note or feedback.