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

如何在自定义分类product-cat页面实现当前分类内产品搜索

解决方案:无需新建搜索模板,通过修改表单+查询钩子实现分类内产品搜索

不需要创建search-products-cat.php这类新模板文件,只需要通过修改搜索表单传递当前分类参数,再用钩子过滤搜索查询,就能实现分类页面内的产品搜索限制,具体步骤如下:

1. 修改searchform.php的搜索表单

在表单中添加两个关键隐藏字段:

  • 指定搜索product自定义文章类型,避免搜到其他内容
  • 当处于product-cat分类页面时,自动传递当前分类的slug

修改后的代码:

<div class="search-wrapper">
    <form role="search" method="get" id="searchform" action="<?php echo esc_url(site_url('products/')); ?>">
        <input type="text" value="" name="s" id="s" placeholder="Search products" />
        <!-- 指定搜索product类型 -->
        <input type="hidden" name="post_type" value="product" />
        <?php
        // 判断当前是否在product-cat分类页面,添加分类slug隐藏字段
        if (is_tax('product-cat')) {
            $current_term = get_queried_object();
            echo '<input type="hidden" name="product-cat" value="' . esc_attr($current_term->slug) . '" />';
        }
        ?>
        <input type="submit" id="searchsubmit" value="" />
    </form>
</div>

2. 添加查询过滤钩子(functions.php中)

通过pre_get_posts钩子,在搜索时自动根据传递的分类参数过滤结果,只返回当前分类下的产品:

add_action('pre_get_posts', 'filter_product_search_by_current_category');
function filter_product_search_by_current_category($query) {
    // 仅处理前台主搜索查询,且是针对product类型的搜索
    if (!is_admin() && $query->is_main_query() && $query->is_search() && isset($query->query_vars['post_type']) && $query->query_vars['post_type'] === 'product') {
        // 如果存在product-cat参数,添加分类筛选条件
        if (isset($_GET['product-cat']) && !empty($_GET['product-cat'])) {
            $query->set('tax_query', array(
                array(
                    'taxonomy' => 'product-cat',
                    'field'    => 'slug',
                    'terms'    => sanitize_text_field($_GET['product-cat']),
                    'operator' => 'IN'
                )
            ));
        }
    }
    return $query;
}

说明

  • 因为你已经将archive-product.php的内容复制到search.php,搜索结果会沿用产品归档的布局,无需额外创建新模板
  • 当用户在taxonomy-product-cat.php页面搜索时,表单会自动携带当前分类的slug,钩子会自动过滤查询,只返回该分类下的产品;在其他页面(比如产品归档页)搜索时,依然会搜索所有产品

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 16:47:29