You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改wp_resource_hints()默认输出的s.w.org DNS预取资源提示?

修改wp_resource_hints()输出,移除s.w.org资源提示

不用替换整个wp_resource_hints()函数,也不用移除钩子,我们可以通过wp_resource_hints这个过滤器来修改返回的资源提示数组,精准去掉s.w.org相关的条目。

具体实现步骤

直接在你的主题functions.php文件(或者自定义插件里)添加以下代码:

add_filter( 'wp_resource_hints', 'remove_s_w_org_resource_hints', 10, 2 );
function remove_s_w_org_resource_hints( $hints, $relation_type ) {
    // 过滤掉所有指向s.w.org的资源提示
    $hints = array_filter( $hints, function( $hint ) {
        // 兼容字符串和数组两种格式的资源提示
        if ( is_string( $hint ) ) {
            return strpos( $hint, 's.w.org' ) === false;
        } elseif ( is_array( $hint ) && isset( $hint['href'] ) ) {
            return strpos( $hint['href'], 's.w.org' ) === false;
        }
        return true;
    } );

    return $hints;
}

代码解释

  • 我们钩子了wp_resource_hints过滤器,用默认优先级10,接收两个核心参数:$hints是当前待输出的资源提示数组,$relation_type是当前处理的资源提示类型(比如dns-prefetch、preconnect等)。
  • 用array_filter遍历所有条目:
    • 若条目是字符串(比如基础的dns-prefetch格式),直接检查是否包含s.w.org,不包含的保留。
    • 若条目是数组(比如带额外属性的preconnect配置),则检查href字段是否包含s.w.org,不包含的保留。
  • 最后返回过滤后的数组,wp_resource_hints()就会输出去掉s.w.org后的内容,完全保留原有钩子的其他功能。

按需调整:只移除特定类型的s.w.org提示

如果你只想移除某一种类型(比如仅dns-prefetch)的s.w.org提示,可以修改函数逻辑,加上对$relation_type的判断:

add_filter( 'wp_resource_hints', 'remove_s_w_org_dns_prefetch', 10, 2 );
function remove_s_w_org_dns_prefetch( $hints, $relation_type ) {
    // 只针对dns-prefetch类型做过滤
    if ( $relation_type !== 'dns-prefetch' ) {
        return $hints;
    }

    $hints = array_filter( $hints, function( $hint ) {
        return strpos( $hint, 's.w.org' ) === false;
    } );

    return $hints;
}

这样其他类型的资源提示不受影响,完全贴合你的需求场景。

内容的提问来源于stack exchange,提问作者lowtechsun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:42:18