如何仅在默认文章类型(Post)的搜索结果页加载自定义脚本

如何仅在默认文章类型(Post)的搜索结果页加载自定义脚本

本文介绍一种精准判断 wordpress 搜索结果页是否仅针对默认文章类型(post)的方法,避免在产品(如 woocommerce product)等自定义文章类型的搜索页误加载脚本。

在 WordPress 开发中,is_search() 是一个常用条件函数,用于判断当前页面是否为搜索结果页。但它的局限性在于:它不区分搜索目标的 post type——无论是搜索文章(post)、页面(page)、商品(product),还是其他自定义文章类型,只要触发了搜索查询,is_search() 均返回 true。

因此,若你希望仅在「默认文章类型(post)」的搜索结果页加载特定脚本(例如增强搜索体验的 JS),而排除 product、portfolio 等自定义类型的结果页,需结合其他条件进行更精细的判断。

✅ 推荐判断逻辑:! is_post_type_archive() && is_search()

根据实践验证,以下条件组合可可靠实现目标:

MaxAI

MaxAI

MaxAI.me是一款功能强大的浏览器AI插件,集成了多种AI模型。

下载

function child_theme_search_custom_js_script() {
    // 仅在「非文章归档页」且「是搜索页」时执行 → 即:普通搜索(默认 post 类型)结果页
    if ( ! is_post_type_archive() && is_search() ) {
        wp_enqueue_script(
            'child-theme-search-js',
            get_stylesheet_directory_uri() . '/js/child-search-custom-js.js',
            array( 'abc-core' ),
            '1.0.0',
            true
        );
    }
}
add_action( 'wp_enqueue_scripts', 'child_theme_search_custom_js_script' );

? 为什么这个组合有效?

  • is_search():确保当前为搜索上下文(有 s 查询参数,且主查询为搜索);
  • ! is_post_type_archive():排除所有按 post type 归档的搜索页(例如 /?post_type=product&s=xxx 或 /product/?s=xxx)。这类 URL 通常由主题或插件显式限定 post_type,WordPress 会将其识别为 post type archive(即使同时是搜索),此时 is_post_type_archive() 返回 true;
  • 因此,! is_post_type_archive() && is_search() 实质上等价于:这是一个通用搜索(未指定 post_type 参数),且结果默认展示 post 类型内容——这正是 WordPress 默认搜索行为。

⚠️ 注意事项:该方案依赖 WordPress 默认查询逻辑。若主题或插件通过 pre_get_posts 强制修改主查询(如将搜索限制为 product 但不设 post_type_archive),需额外校验 $wp_query->get(‘post_type’);如需进一步确保仅含 post(排除 page 或其他类型),可补充: $query_post_types = $wp_query->get(‘post_type’) ?: array(‘post’);
if ( is_search() && ! is_post_type_archive() && in_array(‘post’, (array) $query_post_types) ) { … }

✅ 总结

无需复杂钩子或全局变量,利用 WordPress 原生条件函数的语义组合,即可安全、轻量地实现“仅对默认文章搜索页生效”的逻辑。该方法兼容主流主题与插件(包括 WooCommerce),推荐作为标准实践纳入主题或子主题的脚本加载策略中。

https://www.php.cn/faq/1972414.html

发表回复

Your email address will not be published. Required fields are marked *