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

使用woocommerce_product_query筛选商品描述失效,如何修复?

解决WooCommerce商品描述筛选无效的问题

你之前的方法行不通,核心原因是商品的描述(长/短)不属于自定义字段:

  • 商品长描述存在wp_posts表的post_content字段
  • 商品短描述存在wp_posts表的post_excerpt字段
    而meta_query是用来查询wp_postmeta表中自定义字段的,所以用它搜索_description或_post_excerpt自然找不到数据。

正确实现代码

用woocommerce_product_query_posts_where钩子直接修改查询的WHERE条件,同时处理URL传入的筛选参数:

add_action( 'woocommerce_product_query_posts_where', 'custom_product_description_filter', 10, 2 );
function custom_product_description_filter( $where, $query ) {
    // 仅在前台且存在筛选参数时生效
    if ( ! is_admin() && isset( $_GET['description'] ) && ! empty( $_GET['description'] ) ) {
        global $wpdb;
        // 清理参数,避免SQL注入风险
        $description = sanitize_text_field( $_GET['description'] );
        $like_pattern = '%' . $wpdb->esc_like( $description ) . '%';
        // 添加对长描述和短描述的模糊匹配
        $where .= $wpdb->prepare( 
            " AND ( {$wpdb->posts}.post_content LIKE %s OR {$wpdb->posts}.post_excerpt LIKE %s )", 
            $like_pattern, 
            $like_pattern 
        );
    }
    return $where;
}

可选调整

  • 若只想筛选短描述,删除OR {$wpdb->posts}.post_excerpt LIKE %s部分即可
  • 若只想筛选长描述,删除{$wpdb->posts}.post_content LIKE %s OR部分即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 05:33:27