函数文档

wp_print_scripts()

💡 云策文档标注

概述

wp_print_scripts() 函数用于在文档头部打印指定队列中的脚本。它通常由 admin-header.php 和 'wp_head' 钩子调用,仅在显式传递脚本名称时才实例化 WP_Scripts 对象。

关键要点

  • 函数打印 $handles 队列中的脚本,参数 $handles 可选,默认为 false,表示打印所有队列脚本。
  • 调用时使用全局 $wp_scripts 对象(如果已实例化),否则在需要时初始化。
  • 通过 'wp_print_scripts' 钩子可以在打印前注册或入队新脚本。
  • 返回成功处理的脚本句柄数组,失败时返回空数组。

代码示例

function wp_print_scripts( $handles = false ) {
	global $wp_scripts;

	do_action( 'wp_print_scripts' );

	if ( '' === $handles ) {
		$handles = false;
	}

	_wp_scripts_maybe_doing_it_wrong( __FUNCTION__ );

	if ( ! ( $wp_scripts instanceof WP_Scripts ) ) {
		if ( ! $handles ) {
			return array();
		}
	}

	return wp_scripts()->do_items( $handles );
}

注意事项

  • 函数在每次页面加载时通过 wp_head 调用,避免不必要的实例化以提高性能。
  • 相关函数包括 wp_scripts() 和 WP_Scripts::do_item(),用于初始化和处理脚本项。

📄 原文内容

Prints scripts in document head that are in the $handles queue.

Description

Called by admin-header.php and ‘wp_head’ hook. Since it is called by wp_head on every page load, the function does not instantiate the WP_Scripts object unless script names are explicitly passed.
Makes use of already-instantiated $wp_scripts global if present. Use provided ‘wp_print_scripts’ hook to register/enqueue new scripts.

See also

Parameters

$handlesstring|string[]|falseoptional
Scripts to be printed. Default 'false'.

Default:false

Return

string[] On success, an array of handles of processed WP_Dependencies items; otherwise, an empty array.

Source

function wp_print_scripts( $handles = false ) {
	global $wp_scripts;

	/**
	 * Fires before scripts in the $handles queue are printed.
	 *
	 * @since 2.1.0
	 */
	do_action( 'wp_print_scripts' );

	if ( '' === $handles ) { // For 'wp_head'.
		$handles = false;
	}

	_wp_scripts_maybe_doing_it_wrong( __FUNCTION__ );

	if ( ! ( $wp_scripts instanceof WP_Scripts ) ) {
		if ( ! $handles ) {
			return array(); // No need to instantiate if nothing is there.
		}
	}

	return wp_scripts()->do_items( $handles );
}

Hooks

do_action( ‘wp_print_scripts’ )

Fires before scripts in the $handles queue are printed.

Changelog

Version Description
2.1.0 Introduced.