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

WooCommerce后台商品仅按自定义_meta与标题搜索实现咨询

WooCommerce后台仅搜索商品标题和自定义meta字段实现方案

完整修改后代码

将你主题functions.php中原有的代码替换为以下内容即可:

function m_request_query( $query_vars ) {
    global $typenow;
    global $wpdb;
    global $pagenow;

    if ( 'product' === $typenow && isset( $_GET['s'] ) && 'edit.php' === $pagenow ) {
        $search_term = esc_sql( sanitize_text_field( $_GET['s'] ) );
        $like_term = '%' . $wpdb->esc_like( $search_term ) . '%';
        $meta_key = '_barcode';
        $post_types = array( 'product', 'product_variation' );
        
        // 扩展查询逻辑:同时匹配自定义meta字段或商品标题
        $search_results = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT DISTINCT posts.ID as product_id, posts.post_parent as parent_id 
                FROM {$wpdb->posts} posts 
                LEFT JOIN {$wpdb->postmeta} AS postmeta ON posts.ID = postmeta.post_id 
                WHERE 
                    posts.post_type IN ('" . implode( "','", $post_types ) . "')
                    AND (
                        (postmeta.meta_key = %s AND postmeta.meta_value LIKE %s)
                        OR posts.post_title LIKE %s
                    )
                ORDER BY posts.post_parent ASC, posts.post_title ASC",
                $meta_key,
                $like_term,
                $like_term
            )
        );
        
        $product_ids = wp_parse_id_list( array_merge( 
            wp_list_pluck( $search_results, 'product_id' ), 
            wp_list_pluck( $search_results, 'parent_id' ) 
        ) );
        
        // 无匹配结果时传入无效ID,避免返回全部商品
        if ( empty( $product_ids ) ) {
            $product_ids = array(0);
        }
        
        $query_vars['post__in'] = $product_ids;
        // 禁用默认搜索逻辑,避免匹配商品描述等其他字段
        unset( $query_vars['s'] );
    }

    return $query_vars;
}
add_filter( 'request', 'm_request_query', 20 );

核心改动说明

  • 调整了SQL查询条件,新增了商品标题的模糊匹配规则,实现同时匹配_barcode字段或商品标题的需求
  • 新增空结果兜底逻辑,避免搜索无匹配时后台返回全部商品
  • 最终销毁查询参数中的s字段,彻底屏蔽WordPress默认的全文搜索逻辑,完全排除商品描述、短描述等其他字段的匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 15:00:00