函数文档

wp_print_styles()

💡 云策文档标注

概述

wp_print_styles() 函数用于输出样式队列中的样式,支持通过参数控制输出范围。开发者可通过此函数管理样式加载,并利用相关 Hook 进行扩展。

关键要点

  • 函数用于显示 $handles 队列中的样式,参数 $handles 可选,默认为 false
  • 传递空数组会打印整个队列,传递字符串数组会打印指定样式
  • 成功时返回已处理的 WP_Dependencies 项目句柄数组,否则返回空数组
  • 包含 wp_print_styles Hook,在样式打印前触发,便于开发者介入
  • 与 wp_styles() 和 do_action() 等相关函数配合使用,确保样式系统正确初始化

代码示例

function wp_print_styles( $handles = false ) {
    global $wp_styles;

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

    if ( ! $handles ) {
        /**
         * Fires before styles in the $handles queue are printed.
         *
         * @since 2.6.0
         */
        do_action( 'wp_print_styles' );
    }

    _wp_scripts_maybe_doing_it_wrong( __FUNCTION__ );

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

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

注意事项

  • 参数 $handles 可以是字符串、布尔值或数组,需根据需求正确传递以避免错误输出
  • 在无样式队列时调用可能返回空数组,需检查返回值以确保操作成功
  • 使用 wp_print_styles Hook 时,确保回调函数不会干扰其他样式加载逻辑

📄 原文内容

Displays styles that are in the $handles queue.

Description

Passing an empty array to $handles prints the queue, passing an array with one string prints that style, and passing an array of strings prints those styles.

Parameters

$handlesstring|bool|arrayoptional
Styles 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_styles( $handles = false ) {
	global $wp_styles;

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

	if ( ! $handles ) {
		/**
		 * Fires before styles in the $handles queue are printed.
		 *
		 * @since 2.6.0
		 */
		do_action( 'wp_print_styles' );
	}

	_wp_scripts_maybe_doing_it_wrong( __FUNCTION__ );

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

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

Hooks

do_action( ‘wp_print_styles’ )

Fires before styles in the $handles queue are printed.

Changelog

Version Description
2.6.0 Introduced.