函数文档

wp_add_inline_script()

💡 云策文档标注

概述

wp_add_inline_script() 是 WordPress 核心函数,用于向已注册的脚本添加额外的 JavaScript 代码。它确保代码仅在脚本已入队时添加,并支持指定代码位置(之前或之后)。

关键要点

  • 函数接受三个参数:$handle(脚本句柄)、$data(JavaScript 代码字符串)和 $position(可选,默认为 'after')。
  • 代码添加顺序遵循先进先出原则,后添加的代码可以覆盖先前的声明。
  • 内部调用 WP_Scripts::add_inline_script() 实现功能,并包含安全检查以防止恶意代码注入。
  • 常用于替代 wp_localize_script() 来传递 PHP 数据到 JavaScript,例如通过 JSON 编码创建全局变量。
  • 在块编辑器等现代环境中使用时需注意时机,避免重复添加或延迟问题。

代码示例

// 基本用法:添加内联脚本到已注册脚本
wp_enqueue_script( 'my-script', 'path/to/script.js' );
wp_add_inline_script( 'my-script', 'console.log("Inline script added");', 'after' );

// 传递 PHP 数据到 JavaScript(替代 wp_localize_script)
$data = array( 'ajaxUrl' => admin_url( 'admin-ajax.php' ) );
wp_add_inline_script( 'my-script', 'const MY_DATA = ' . json_encode( $data ) . ';', 'before' );

// 为无依赖脚本添加代码(通过注册空脚本)
wp_register_script( 'dummy-js', '', array(), '', true );
wp_enqueue_script( 'dummy-js' );
wp_add_inline_script( 'dummy-js', "console.log('Loaded in footer');" );

注意事项

  • 确保目标脚本已通过 wp_enqueue_script() 或类似函数入队,否则内联代码不会添加。
  • 避免在 $data 中包含闭合 script 标签,函数会进行安全检查并发出警告。
  • 在块主题或编辑器环境中,内联脚本可能需要在特定钩子(如 wp_footer)中调用以避免时机问题。
  • 多次调用同一句柄时,代码会按添加顺序输出,需注意潜在的覆盖或重复问题。

📄 原文内容

Adds extra code to a registered script.

Description

Code will only be added if the script is already in the queue.
Accepts a string $data containing the code. If two or more code blocks are added to the same script $handle, they will be printed in the order they were added, i.e. the latter added code can redeclare the previous.

See also

Parameters

$handlestringrequired
Name of the script to add the inline script to.
$datastringrequired
String containing the JavaScript to be added.
$positionstringoptional
Whether to add the inline script before the handle or after. Default 'after'.

Return

bool True on success, false on failure.

Source

function wp_add_inline_script( $handle, $data, $position = 'after' ) {
	_wp_scripts_maybe_doing_it_wrong( __FUNCTION__, $handle );

	if ( false !== stripos( $data, '</script>' ) ) {
		_doing_it_wrong(
			__FUNCTION__,
			sprintf(
				/* translators: 1: <script>, 2: wp_add_inline_script() */
				__( 'Do not pass %1$s tags to %2$s.' ),
				'<code><script></code>',
				'<code>wp_add_inline_script()</code>'
			),
			'4.5.0'
		);
		$data = trim( preg_replace( '#<script[^>]*>(.*)</script>#is', '$1', $data ) );
	}

	return wp_scripts()->add_inline_script( $handle, $data, $position );
}

Changelog

Version Description
4.5.0 Introduced.

User Contributed Notes

  1. Skip to note 8 content

    Apparently we should now use wp_add_inline_script instead of wp_localize_script to expose a global object that needs to be used by your script.

    So, while previously you could (and still can) do this:

    wp_enqueue_script( 'wpdocs-my-script', 'https://url-to/my-script.js' );
    wp_localize_script( 'wpdocs-my-script', 'MYSCRIPT', array(
        'ajaxUrl' => admin_url( 'admin-ajax.php' ),
        'otherParam' => 'some value',
    ) );

    It seems that it’s now recommended to do it like this (which I personally believe is a lot uglier):

    wp_enqueue_script( 'wpdocs-my-script', 'https://url-to/my-script.js' );
    wp_add_inline_script( 'wpdocs-my-script', 'const MYSCRIPT = ' . json_encode( array(
        'ajaxUrl' => admin_url( 'admin-ajax.php' ),
        'otherParam' => 'some value',
    ) ), 'before' );

    Note that you need to add 'before' as the third parameter to the wp_add_inline_script function.

    Now, in your JS script you can access these PHP parameters like this:

    console.log( MYSCRIPT.ajaxUrl ); // output: "<a href="https://your-site/wp-admin/admin-ajax.php&quot" rel="nofollow ugc">https://your-site/wp-admin/admin-ajax.php"</a>;
    console.log( MYSCRIPT.otherParam ); // output: "some value"

  2. Skip to note 9 content

    The following code can be used to easily add Typekit’s JavaScript to your theme:

    function mytheme_enqueue_typekit() {
       wp_enqueue_script( 'mytheme-typekit', 'https://use.typekit.net/.js', array(), '1.0' );
       wp_add_inline_script( 'mytheme-typekit', 'try{Typekit.load({ async: true });}catch(e){}' );
    }
    add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_typekit' );

    Which results in:

    <script type="text/javascript" src="<a href="https://use.typekit.net/.js?ver=1.0"></script&gt" rel="nofollow ugc">https://use.typekit.net/.js?ver=1.0"></script&gt</a>;
    <script type="text/javascript"> try{Typekit.load({ async: true });}catch(e){} </script>

    From https://make.wordpress.org/core/2016/03/08/enhanced-script-loader-in-wordpress-4-5/

  3. Skip to note 10 content

    Add CSS Style without dependency

    wp_register_style( 'myprefix-dummy-css', false );
    wp_enqueue_style( 'myprefix-dummy-css' );
    wp_add_inline_style( 'myprefix-dummy-css', "body *{ box-sizing: inherit; }");

    Add JavaScript Code without dependency

    wp_register_script( 'myprefix-dummy-js-header', '',);
    wp_enqueue_script( 'myprefix-dummy-js-header' );
    wp_add_inline_script( 'myprefix-dummy-js-header', "console.log('loaded in header');");

    Add JavaScript Code with jQuery dependency

    wp_register_script( 'myprefix-dummy-js-footer', '', array("jquery"), '', true );
    wp_enqueue_script( 'myprefix-dummy-js-footer'  );
    wp_add_inline_script( 'myprefix-dummy-js-footer', "console.log('loaded in footer');");

  4. Skip to note 11 content

    NOTE: with new block themes such as Twenty Twenty Two, wp_localize_script/wp_add_inline_script will no longer work if called too late such as in a shortcode rendering callback function. To achieve this you will need to make use of an anonymous function call hooked on wp_footer action,

    $data=array();// your data object you want to pass to your front-end script.
    $localise = json_encode($data);
    add_action('wp_footer', function() use ($localise){
      printf('<script type="text/javascript">var myData = %s</script>', $localise);
    });

  5. Skip to note 12 content

    this is handy function when you want to make sure your anonymous function uses an object that is instantiated using a javascript library that can potentially clash with other versions loaded by other plugins or by WordPress core itself. For example, if you need to use a different version of jQuery, you can do the following,

    wp_register_script( 'jquery3.2.1', 'https://code.jquery.com/jquery-3.2.1.min.js' );
    wp_add_inline_script( 'jquery3.2.1', 'var jQuery3_2_1 = $.noConflict(true);' );
    wp_enqueue_script( 'plugin-javascript', plugins_url( 'js.js', __FILE__ ), array( 'jquery3.2.1' ) );

    this will instantiate a new jQuery object `jquery3_2_1` right after the jquery library v3.2.1 is loaded by the browser, ensuring it has the right version references, which you can then pass as an attribute the `js.js` script,

    ( function( $ ) { //$ now uses v3.2.1 of jquery.
      // Alert jQuery version.
      alert($.fn.jquery);
      // Plugin/theme code should go here.
    }( jQuery3_2_1 ) );

  6. Skip to note 13 content

    If you are adding an inline script to the editor in the new recommended way (see: https://developer.wordpress.org/block-editor/how-to-guides/enqueueing-assets-in-the-editor/), then it’s important to note that calling `wp_add_inline_script() ` twice will duplicate the inline script code.

    For example, if you want to add an inline script to both the editor itself and the editor content (in an iframed editor), then you should (using the recommendation) enqueue the same script with both `enqueue_block_editor_assets` and `enqueue_block_assets`. However, in this case make sure to only call `wp_add_inline_script() ` once to avoid script duplication (the registration and source code stick around even though the queue gets cleared out between the editor and editor content enqueuing).

    You can check for prior registration and also enqueue with something like this:

    “`php
    if ( ! wp_script_is( $handle, ‘registered’ ) ) {
    wp_register_script( $handle, false );
    wp_add_inline_script( $handle, $src );
    }
    wp_enqueue_script( $handle, ”, $deps, false, $args );
    “`

  7. Skip to note 14 content

    For adding inline script

    function theme_prefix_enqueue_script() {
       wp_enqueue_script( 'main-js', '/main.js', array(), '1.0' );
       wp_add_inline_script( 'main-js', 'alert("hello world");' );
    }
    add_action( 'wp_enqueue_scripts', 'theme_prefix_enqueue_script' );

    For jQuery-dependent scripts use this:

    function theme_prefix_enqueue_script() {
       if ( ! wp_script_is( 'jquery', 'done' ) ) {
         wp_enqueue_script( 'jquery' );
       }
       wp_add_inline_script( 'jquery-migrate', 'jQuery(document).ready(function(){});' );
    }
    add_action( 'wp_enqueue_scripts', 'theme_prefix_enqueue_script' );