所有在我的情况下,我想得到的性别,年龄,城市等职位的结果。。。我正在使用此查询。如果我有任何变量,如年龄、城市、性别,那么“AND”操作将执行并得到该变量的唯一结果。
Note: 考虑那些我没有像城市这样的变量,但它应该适用于性别和;状态
我的问题是
$gender = $_GET[\'gender\'];
$city = $_GET[\'city\'];
$state = $_GET[\'state\'];
$wp_query = new WP_Query( array(
\'post_type\' => \'profile\',
\'meta_query\' => array(
\'relation\' => \'AND\',
array(\'meta_key\' => \'wpcf-gender\', \'meta_value\' => $_GET[\'gender\'], \'meta_compare\' => \'==\'),
array(\'meta_key\' => \'wpcf-city\', \'meta_value\' => $_GET[\'city\'], \'meta_compare\' => \'==\'),
array(\'meta_key\' => \'wpcf-state\', \'meta_value\' => $_GET[\'state\'], \'meta_compare\' => \'==\')
),
\'paged\' => $paged )
);
最合适的回答,由SO网友:Sisir 整理而成
这里是对代码的修改,如果设置了某些$GET键,则可以添加元查询。
$query_array = array(\'relation\' => \'AND\');
if(isset($_GET[\'gender\']) && !empty($_GET[\'gender\'])){
$gender = $_GET[\'gender\'];
array_push($query_array, array(\'key\' => \'wpcf-gender\', \'value\' => $gender, \'compare\' => \'=\'));
}
if(isset($_GET[\'city\']) && !empty($_GET[\'city\'])){
$city = $_GET[\'city\'];
array_push($query_array, array(\'key\' => \'wpcf-city\', \'value\' => $city, \'compare\' => \'=\'));
}
if(isset($_GET[\'state\']) && !empty($_GET[\'state\'])){
$state = $_GET[\'state\'];
array_push($query_array, array(\'key\' => \'wpcf-state\', \'value\' => $state, \'compare\' => \'=\'));
}
$wp_query = new WP_Query( array(
\'post_type\' => \'profile\',
//\'query\' => $query_array, should be \'meta_query\' => $query_array,
\'meta_query\' => $query_array,
\'paged\' => $paged )
);
Reference:
array_push()
:
http://php.net/manual/en/function.array-push.php