admin_print_scripts
云策文档标注
概述
admin_print_scripts 是一个 WordPress 动作钩子,在管理后台所有页面的脚本打印时触发。主要用于在管理页面头部输出内联 JavaScript 代码,但不应用于排队样式或脚本。
关键要点
- admin_print_scripts 钩子在管理后台所有页面的脚本打印时触发,用于输出内联 JavaScript。
- 不应使用此钩子来排队样式或脚本,应使用 admin_enqueue_scripts 钩子代替。
- admin_print_scripts 用于在管理页面头部插入内联脚本,而 admin_print_footer_scripts 用于在页脚插入。
- 从 PHP 向 JavaScript 传递值时,应使用 wp_json_encode() 以避免 XSS 安全漏洞。
代码示例
function admin_inline_js(){
echo "";
}
add_action( 'admin_print_scripts', 'admin_inline_js' );注意事项
使用 wp_json_encode() 准备传递给 JavaScript 的值,确保安全性。
原文内容
Fires when scripts are printed for all admin pages.
Source
do_action( 'admin_print_scripts' );
Changelog
| Version | Description |
|---|---|
| 2.1.0 | Introduced. |
Skip to note 2 content
Steven Lin
Migrate from Codex:
Basic Examples:
function admin_inline_js(){ echo "<script type='text/javascript'>n"; echo 'var pluginUrl = ' . wp_json_encode( WP_PLUGIN_URL . '/my_plugin/' ) . ';'; echo "n</script>"; } add_action( 'admin_print_scripts', 'admin_inline_js' );Result:
var pluginUrl = “http://website.com/wp-content/plugins/my_plugin/”;
Note that we use wp_json_encode() to prepare the value for pluginURL before embedding it in the JavaScript code. It is important to always use wp_json_encode() when passing values from PHP to JavaScript, to avoid the possibility of XSS security vulnerabilities.