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

WooCommerce空搜索结果重定向至自定义页面问题求助

修复WooCommerce空搜索结果重定向的致命错误及代码优化

原代码的致命错误原因

原代码里的strcasecmp( $_GET['s'] )调用错误,strcasecmp()函数必须传入两个字符串参数,你只传了一个,直接导致PHP致命错误。另外这段代码也没实现你要的「返回0条结果的产品搜索」重定向需求,仅判断了搜索关键词为空的情况。

修复后的代码

add_action( 'template_redirect', 'redirect_empty_product_search_result', 20 );
function redirect_empty_product_search_result() {
    // 仅处理WooCommerce产品搜索请求
    if ( isset( $_GET['s'], $_GET['post_type'] ) && $_GET['post_type'] === 'product' ) {
        global $wp_query;
        
        // 确认搜索结果为0条
        if ( $wp_query->found_posts === 0 ) {
            wp_safe_redirect( home_url( '/empty-search/' ) );
            exit();
        }
    }
}

代码说明

  • 调整钩子优先级为20,确保WordPress完成查询后再判断结果数量
  • 增加post_type=product判断,仅针对WooCommerce产品搜索生效
  • 用$wp_query->found_posts精准获取搜索结果总数,判断是否为0
  • 借助home_url()拼接重定向URL,适配不同站点的URL配置
  • 保留wp_safe_redirect()保障重定向操作的安全性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 07:32:05