WooCommerce后台关联产品搜索优化:仅检索商品标题
解决WooCommerce后台Upsells/Cross-sells仅搜索商品标题的问题
要限制后台编辑页里追加销售(Upsells)和交叉销售(Cross-sells)的产品搜索仅匹配商品标题,可以用WooCommerce提供的钩子调整查询逻辑,以下是两种可行方案:
方案1:修改查询的搜索字段(推荐)
利用woocommerce_ajax_product_search_query钩子直接指定搜索仅针对商品标题,无需手动编写SQL:
add_filter( 'woocommerce_ajax_product_search_query', 'restrict_upsell_crossell_search_to_title', 10, 1 ); function restrict_upsell_crossell_search_to_title( $query_args ) { // 仅作用于后台的Upsells/Cross-sells AJAX搜索 if ( is_admin() && defined( 'DOING_AJAX' ) && DOING_AJAX && isset( $_POST['action'] ) && $_POST['action'] === 'woocommerce_json_search_products_and_variations' ) { // 强制仅搜索商品标题 $query_args['search_columns'] = array( 'post_title' ); } return $query_args; }
方案2:直接修改SQL WHERE子句
如果需要更精细的控制,可以用woocommerce_product_search_posts_where钩子替换默认的搜索条件:
add_filter( 'woocommerce_product_search_posts_where', 'custom_upsell_search_where_clause', 10, 2 ); function custom_upsell_search_where_clause( $where, $query_vars ) { // 限定场景:后台AJAX搜索Upsells/Cross-sells if ( is_admin() && defined( 'DOING_AJAX' ) && DOING_AJAX && isset( $_POST['action'] ) && $_POST['action'] === 'woocommerce_json_search_products_and_variations' ) { $search_term = esc_sql( $query_vars['s'] ); // 只保留标题匹配的条件,移除描述等其他字段的搜索 $where = " AND (wp_posts.post_title LIKE '%{$search_term}%') "; } return $where; }
使用说明
- 将上述代码添加到当前主题的
functions.php文件,或自定义插件中 - 两个方案都只会作用于后台编辑页的Upsells/Cross-sells搜索框,不会影响前端或其他后台搜索功能
- 测试前建议清空缓存,确保钩子生效
内容的提问来源于stack exchange,提问作者reactive
相关产品推荐
相关产品推荐

