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

WooCommerce:将商品分类标题与描述纳入商品搜索查询

解决方案:WooCommerce搜索包含商品分类名称和描述

你原代码的问题在于tax_query无法直接匹配分类描述,且field参数不支持description,terms搭配LIKE的用法也不符合WP_Query规则。要实现需求,需通过posts_join和posts_where钩子手动关联分类表,添加分类名称/描述的匹配条件,同时保留商品自身的搜索逻辑。

完整代码实现

// 关联分类表,为搜索分类信息做准备
function wc_search_include_product_cat( $join, $query ) {
    global $wpdb;

    // 仅处理前台商品搜索
    if ( ! is_admin() && $query->is_search && $query->get( 'post_type' ) === 'product' ) {
        $join .= " LEFT JOIN {$wpdb->term_relationships} tr ON {$wpdb->posts}.ID = tr.object_id
                  LEFT JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
                  LEFT JOIN {$wpdb->terms} t ON tt.term_id = t.term_id
                  WHERE tt.taxonomy = 'product_cat'";
    }
    return $join;
}
add_filter( 'posts_join', 'wc_search_include_product_cat', 10, 2 );

// 修改搜索条件,添加分类名称和描述的匹配
function wc_search_include_product_cat_where( $where, $query ) {
    global $wpdb;

    // 仅处理前台商品搜索
    if ( ! is_admin() && $query->is_search && $query->get( 'post_type' ) === 'product' ) {
        $search_term = $query->get( 's' );
        $escaped_term = $wpdb->esc_like( $search_term );

        // 保留商品自身搜索逻辑,同时加入分类匹配条件
        $where = str_replace(
            "AND ({$wpdb->posts}.post_title LIKE '%{$escaped_term}%' OR {$wpdb->posts}.post_content LIKE '%{$escaped_term}%')",
            "AND (
                {$wpdb->posts}.post_title LIKE '%{$escaped_term}%' 
                OR {$wpdb->posts}.post_content LIKE '%{$escaped_term}%'
                OR t.name LIKE '%{$escaped_term}%'
                OR tt.description LIKE '%{$escaped_term}%'
            )",
            $where
        );
    }
    return $where;
}
add_filter( 'posts_where', 'wc_search_include_product_cat_where', 10, 2 );

// 限定搜索类型为商品,保留原有分页逻辑
function wc_search_set_product_post_type( $query ) {
    if ( $query->is_search && ! is_admin() ) {
        $query->set( 'post_type', 'product' );
        $query->set( 'wc_query', 'product_query' );

        // 保留你原有的分页控制
        if ( isset( $_GET['showall'] ) && $_GET['showall'] == 1 ) {
            $query->set( 'paged', 1 );
            $query->set( 'posts_per_page', -1 );
        } else {
            $query->set( 'posts_per_page', 12 );
        }
    }
    return $query;
}
add_filter( 'pre_get_posts', 'wc_search_set_product_post_type' );

代码说明

  1. posts_join钩子:关联商品表与分类关系、分类taxonomy、分类术语表,限定只处理product_cat分类,为匹配分类信息提供数据基础。
  2. posts_where钩子:在原有商品标题/描述的搜索条件外,添加分类名称(t.name)和分类描述(tt.description)的模糊匹配,所有条件用OR连接,满足任一条件即可被检索。
  3. pre_get_posts钩子:确保搜索仅针对商品类型,同时保留你原有的分页和showall逻辑。

效果验证

当搜索pet时,即使商品自身标题/描述不含该词,只要所属分类的名称或描述包含pet,该商品就会出现在搜索结果中,且不会展示分类本身。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 13:25:31