我现在终于可以工作了,如下所示:
首先我找到了原件wp_dependencies_unique_hosts()
来自WordPress代码的函数(它位于一个名为general template.php的文件中),我复制了它,但给它起了一个新名称:wp_dependencies_unique_urls()
.
我观察到此函数正在使用wp_parse_url()
从脚本和样式列表中获取每个URL的主机部分。换句话说,它放弃了这个计划,这就是我遇到问题的原因。
因此,我修改了函数以包含该方案-这里是其整体:
function wp_dependencies_unique_urls() {
global $wp_scripts, $wp_styles;
$unique_urls = 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;
}
$dependency = $dependencies->registered[ $handle ];
$parsed = wp_parse_url( $dependency->src );
if ( ! empty( $parsed[\'host\'] ) && ! in_array( $parsed[\'host\'], $unique_urls ) && $parsed[\'host\'] !== $_SERVER[\'SERVER_NAME\'] ) {
$unique_urls[] = $parsed[\'scheme\'] . \'://\' . $parsed[\'host\'];
}
}
}
}
return $unique_urls;
}
如你所见,我改变的主要内容是:
$unique_urls[] = $parsed[\'scheme\'] . \'://\' . $parsed[\'host\'];
我希望这是将方案添加到每个URL开头的最佳方式。
接下来,我修改了我的原始函数(来自上面的原始问题),所以它调用了我创建的这个新函数:
function dns_prefetch_to_preconnect( $urls, $relation_type ) {
if ( \'dns-prefetch\' === $relation_type ) {
$urls = [];
}
if ( \'preconnect\' === $relation_type ) {
$urls = wp_dependencies_unique_urls();
}
return $urls;
}
add_filter( \'wp_resource_hints\', \'dns_prefetch_to_preconnect\', 0, 2 );
哎哟,真管用!现在,我的页面标题中有了有效的“预连接”链接,这些链接使用与原始排队脚本和样式相同的方案-http或https!
如果我愿意,我可以将我的两个函数合并为一个大函数以简化:
function dns_prefetch_to_preconnect( $urls, $relation_type ) {
global $wp_scripts, $wp_styles;
$unique_urls = 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;
}
$dependency = $dependencies->registered[ $handle ];
$parsed = wp_parse_url( $dependency->src );
if ( ! empty( $parsed[\'host\'] ) && ! in_array( $parsed[\'host\'], $unique_urls ) && $parsed[\'host\'] !== $_SERVER[\'SERVER_NAME\'] ) {
$unique_urls[] = $parsed[\'scheme\'] . \'://\' . $parsed[\'host\'];
}
}
}
}
if ( \'dns-prefetch\' === $relation_type ) {
$urls = [];
}
if ( \'preconnect\' === $relation_type ) {
$urls = $unique_urls;
}
return $urls;
}
add_filter( \'wp_resource_hints\', \'dns_prefetch_to_preconnect\', 0, 2 );