函数文档

wp_dependencies_unique_hosts()

💡 云策文档标注

概述

wp_dependencies_unique_hosts() 函数用于获取所有已入队脚本和样式的唯一主机名列表。它通过解析依赖项的 src 属性,提取并过滤出非本地主机名。

关键要点

  • 函数返回一个字符串数组,包含入队脚本和样式的唯一主机名。
  • 内部遍历 $wp_scripts 和 $wp_styles 全局变量,检查 WP_Dependencies 实例及其队列。
  • 使用 wp_parse_url() 解析依赖项的 src,并排除本地服务器主机名($_SERVER['SERVER_NAME'])。
  • 函数自 WordPress 4.6.0 版本引入。

代码示例

function wp_dependencies_unique_hosts() {
    global $wp_scripts, $wp_styles;

    $unique_hosts = array();

    foreach ( array( $wp_scripts, $wp_styles ) as $dependencies ) {
        if ( $dependencies instanceof WP_Dependencies && ! empty( $dependencies->queue ) ) {
            foreach ( $dependencies->queue as $handle ) {
                if ( ! isset( $dependencies->registered[ $handle ] ) ) {
                    continue;
                }

                /* @var _WP_Dependency $dependency */
                $dependency = $dependencies->registered[ $handle ];
                $parsed     = wp_parse_url( $dependency->src );

                if ( ! empty( $parsed['host'] )
                    && ! in_array( $parsed['host'], $unique_hosts, true ) && $parsed['host'] !== $_SERVER['SERVER_NAME']
                ) {
                    $unique_hosts[] = $parsed['host'];
                }
            }
        }
    }

    return $unique_hosts;
}

📄 原文内容

Retrieves a list of unique hosts of all enqueued scripts and styles.

Return

string[] A list of unique hosts of enqueued scripts and styles.

Source

function wp_dependencies_unique_hosts() {
	global $wp_scripts, $wp_styles;

	$unique_hosts = array();

	foreach ( array( $wp_scripts, $wp_styles ) as $dependencies ) {
		if ( $dependencies instanceof WP_Dependencies && ! empty( $dependencies->queue ) ) {
			foreach ( $dependencies->queue as $handle ) {
				if ( ! isset( $dependencies->registered[ $handle ] ) ) {
					continue;
				}

				/* @var _WP_Dependency $dependency */
				$dependency = $dependencies->registered[ $handle ];
				$parsed     = wp_parse_url( $dependency->src );

				if ( ! empty( $parsed['host'] )
					&& ! in_array( $parsed['host'], $unique_hosts, true ) && $parsed['host'] !== $_SERVER['SERVER_NAME']
				) {
					$unique_hosts[] = $parsed['host'];
				}
			}
		}
	}

	return $unique_hosts;
}

Changelog

Version Description
4.6.0 Introduced.