向注册的脚本添加额外的代码。
原型
wp_add_inline_script( string $handle, string $data, string $position = 'after' )
描述
只有当脚本已经在队列中时才会添加代码。接受包含代码的字符串$数据。如果将两个或多个代码块添加到同一个脚本$ handle中,它们将按照添加的顺序打印,即后者添加的代码可以重新声明前一个。
参考:
- WP_Scripts::add_inline_script()
参数
$handle
(string)
(Required)
要将内联脚本添加到的脚本的名称。
$data
(string)
(Required)
包含要添加的javascript的字符串。
$position
(string)
(Optional)
是否在句柄之前或之后添加内联脚本。
返回值
(bool)
成功时是真的,失败时是假的。
源文件
路径:wp-includes/functions.wp-scripts.php
<?php
...
function wp_add_inline_script( $handle, $data, $position = 'after' ) {
_wp_scripts_maybe_doing_it_wrong( __FUNCTION__ );
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 );
}
...
?>
其他
英文文档:https://developer.wordpress.org/reference/functions/wp_add_inline_script/