使用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
相关产品推荐
相关产品推荐

