As of WordPress 4.6.0 there is a resource hints API that automatically adds all unique enqueued domains, which you can override with wp_resource_hints
- you should only use the following answer if you\'re stuck with < 4.6.0
你所能做的就是提高你的钩的优先级:
add_action( \'wp_head\', \'dns_prefetch\', 0 /* Highest priority */ );
但这是否会将我的代码放在标记的开头之后?
否,但它将在附加到的任何其他函数之前输出wp_head
i、 e.其他<link />
\'s、 大多数样式表、插件脚本等。
把它放在后面<head>
您很可能需要编辑主题的header.php
直接地
真的没有别的办法吗?
您可以通过一些输出缓冲来解决它:
function wpse_177395_start_buffering( $template ) {
ob_start();
return $template;
}
add_filter( \'template_include\', \'wpse_177395_start_buffering\' );
function wpse_177395_flush() {
$content = ob_get_clean();
$content = preg_replace( \'/<head[^>]*>/\', \'$0
<link rel="dns-prefetch" href="//cdn.mysite.com" />
<link rel="dns-prefetch" href="//fonts.googleapis.com" />\',
$content
);
echo $content;
}
add_action( \'wp_head\', \'wpse_177395_flush\', 0 );