wp_get_inline_script_tag()
云策文档标注
概述
wp_get_inline_script_tag() 函数用于构建一个内联脚本标签,支持自定义属性,并处理 HTML 与 XHTML 文档的兼容性问题。它通过过滤器和相关函数提供灵活的脚本管理。
关键要点
- 函数核心功能是生成内联 script 标签,可注入属性如 type、nonce 等。
- 自动处理 HTML5 和非 HTML5 文档的脚本类型属性,确保兼容性。
- 提供 wp_inline_script_attributes 过滤器,允许开发者修改脚本属性。
- 与 wp_sanitize_script_attributes() 等函数协同工作,用于脚本加载和主题支持检查。
- 自 WordPress 5.7.0 版本引入,常用于前端脚本注入,如 Google Analytics。
代码示例
// 示例:添加 Google Analytics 脚本到文档头部
function wpdocs_add_scripts_head() {
$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 );注意事项
- 在非 HTML5 文档中,需注意脚本类型属性以避免 XHTML 解析错误。
- 使用 wp_inline_script_attributes 过滤器时,避免覆盖现有属性,建议直接修改数组元素而非返回新数组。
- 此函数有助于实现 CSP(内容安全策略)合规,但需在前后端测试。
原文内容
Constructs an inline script tag.
Description
It is possible to inject attributes in the <script> tag via the ‘wp_inline_script_attributes’ filter.
Automatically injects type attribute if needed.
Parameters
$datastringrequired-
Data for script tag: JavaScript, importmap, speculationrules, etc.
$attributesarrayoptional-
Key-value pairs representing
<script>tag attributes.Default:
array()
Source
function wp_get_inline_script_tag( $data, $attributes = array() ) {
$is_html5 = current_theme_supports( 'html5', 'script' ) || is_admin();
if ( ! isset( $attributes['type'] ) && ! $is_html5 ) {
// Keep the type attribute as the first for legacy reasons (it has always been this way in core).
$attributes = array_merge(
array( 'type' => 'text/javascript' ),
$attributes
);
}
/*
* XHTML extracts the contents of the SCRIPT element and then the XML parser
* decodes character references and other syntax elements. This can lead to
* misinterpretation of the script contents or invalid XHTML documents.
*
* Wrapping the contents in a CDATA section instructs the XML parser not to
* transform the contents of the SCRIPT element before passing them to the
* JavaScript engine.
*
* Example:
*
* <script>console.log('…');</script>
*
* In an HTML document this would print "…" to the console,
* but in an XHTML document it would print "…" to the console.
*
* <script>console.log('An image is <img> in HTML');</script>
*
* In an HTML document this would print "An image is <img> in HTML",
* but it's an invalid XHTML document because it interprets the `<img>`
* as an empty tag missing its closing `/`.
*
* @see https://www.w3.org/TR/xhtml1/#h-4.8
*/
if (
! $is_html5 &&
(
! isset( $attributes['type'] ) ||
'module' === $attributes['type'] ||
str_contains( $attributes['type'], 'javascript' ) ||
str_contains( $attributes['type'], 'ecmascript' ) ||
str_contains( $attributes['type'], 'jscript' ) ||
str_contains( $attributes['type'], 'livescript' )
)
) {
/*
* If the string `]]>` exists within the JavaScript it would break
* out of any wrapping CDATA section added here, so to start, it's
* necessary to escape that sequence which requires splitting the
* content into two CDATA sections wherever it's found.
*
* Note: it's only necessary to escape the closing `]]>` because
* an additional `', ']]]]> */", $data );
}
$data = "n" . trim( $data, "nr " ) . "n";
/**
* 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.
* @param string $data Inline data.
*/
$attributes = apply_filters( 'wp_inline_script_attributes', $attributes, $data );
return sprintf( "<script%s>%s</script>n", wp_sanitize_script_attributes( $attributes ), $data );
}
Hooks
- apply_filters( ‘wp_inline_script_attributes’, array $attributes, string $data )
-
Filters attributes to be added to a script tag.
Changelog
| Version | Description |
|---|---|
| 5.7.0 | Introduced. |
Skip to note 3 content
albertomake
A nice way to include Google Analytics and other scripts in the 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:
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 async src="%5B/php%5D” rel=”nofollow ugc”>https://www.google-analytics.com/analytics.js”>%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/
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';"scripttag. Would be better to set$attr['nonce']on the existing array rather than return a new array.