WordPress & ACF多条件筛选问题:城市+分类组合筛选失效
问题:WordPress多条件元数据筛选失效
单城市筛选可正常返回结果(如访问https://test.qualitybusinessawards.com/search?city=Chicago),但同时使用城市+分类组合筛选时(如https://test.qualitybusinessawards.com/search?city=Chicago&category=Dentist),结果仅显示所有牙医,未限定芝加哥地区。
原实现代码如下:
function my_pre_get_posts( $query ) { // do not modify queries in the admin if( is_admin() ) { return $query; } // only modify queries for 'event' post type if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'post' ) { // allow the url to alter the query $city = isset($_GET['city']); $category = isset($_GET['category']); if( $city ) { $query->set('meta_key', 'city'); $query->set('meta_value', $_GET['city']); } if( $category ) { $query->set('meta_key', 'category', '='); $query->set('meta_value', $_GET['category']); } } // return return $query; } add_action('pre_get_posts', 'my_pre_get_posts');
问题分析
- 重复覆盖meta_key:两次调用
$query->set('meta_key')会覆盖前一次设置,最终只有category的元数据筛选生效,城市条件被丢弃。 - 单条件写法限制:直接用
meta_key和meta_value仅支持单个元数据筛选,多条件需通过meta_query数组构建逻辑关系。 - 错误的set方法调用:
$query->set('meta_key', 'category', '=')传入了3个参数,set方法仅接受键和值两个参数,第三个参数无效。
修复后的代码
function my_pre_get_posts( $query ) { // 后台查询不做修改 if( is_admin() ) { return $query; } // 仅针对post类型的查询进行修改 if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'post' ) { $meta_query = array(); // 添加城市筛选条件 if( isset($_GET['city']) && !empty($_GET['city']) ) { $meta_query[] = array( 'key' => 'city', 'value' => sanitize_text_field($_GET['city']), 'compare' => '=' ); } // 添加分类筛选条件 if( isset($_GET['category']) && !empty($_GET['category']) ) { $meta_query[] = array( 'key' => 'category', 'value' => sanitize_text_field($_GET['category']), 'compare' => '=' ); } // 存在筛选条件时,设置meta_query if( !empty($meta_query) ) { // 多条件默认采用AND逻辑,满足"城市+分类"同时匹配的需求 $query->set('meta_query', $meta_query); } } return $query; } add_action('pre_get_posts', 'my_pre_get_posts');
优化说明
- 增加
!empty()判断,避免空参数触发无效筛选 - 使用
sanitize_text_field()过滤GET参数,防范SQL注入风险 - 采用
meta_query数组管理多筛选条件,确保多个条件同时生效(默认逻辑为AND)
内容的提问来源于stack exchange,提问作者Leonard JR
相关产品推荐
相关产品推荐

