wp_get_inline_script_tag( string $javascript, array $attributes = array() )

Wraps inline JavaScript in tag.


Description Description

It is possible to inject attributes in the <script> tag via the ‘wp_script_attributes’ filter. Automatically injects type attribute if needed.


Top ↑

Parameters Parameters

$javascript

(string) (Required) Inline JavaScript code.

$attributes

(array) (Optional) Key-value pairs representing <script> tag attributes.

Default value: array()


Top ↑

Return Return

(string) String containing inline JavaScript code wrapped around <script> tag.


Top ↑

Source Source

File: wp-includes/script-loader.php

function wp_get_inline_script_tag( $javascript, $attributes = array() ) {
	if ( ! isset( $attributes['type'] ) && ! is_admin() && ! current_theme_supports( 'html5', 'script' ) ) {
		$attributes['type'] = 'text/javascript';
	}
	/**
	 * Filters attributes to be added to a script tag.
	 *
	 * @since 5.7.0
	 *
	 * @param array $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.
	 */
	$attributes = apply_filters( 'wp_inline_script_attributes', $attributes, $javascript );

	$javascript = "\n" . trim( $javascript, "\n\r " ) . "\n";

	return sprintf( "<script%s>%s</script>\n", wp_sanitize_script_attributes( $attributes ), $javascript );
}


Top ↑

Changelog Changelog

Changelog
Version Description
5.7.0 Introduced.

Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note 1 content
    Contributed by albertomake

    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>

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

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