我有一个包含3个字段的搜索表单:城市属性类型和房间所有字段都是选择类型输入。
如果我为每个字段选择值,我会得到正确的结果。
例如:
city= Los Angeles
property type = apartment
room = 3
但是如果只选择城市和属性类型,而不选择房间的值(假设空值为
all
). 我没有得到任何结果。我希望能在洛杉矶找到所有的公寓。
这是我到目前为止得到的wp查询。
if (isset($_GET[\'front-side-prop-search\'])){
$args = array(
\'posts_per_page\' => 9,
\'post_type\' => \'property\',
\'meta_query\' => array(
\'relation \' => \'AND\',
array(
\'key\' => \'prop_city\',
\'value\' => $city,
\'compare\' => \'=\',
\'meta_query\' => array(
\'relation \' => \'OR\',
array(
\'key\' => \'prop_city\',
\'value\' => \'All\',
\'compare\' => \'NOT LIKE\',
),
),
),
array(
\'key\' => \'prop_type\',
\'value\' => $type,
\'compare\' => \'=\'
),
array(
\'key\' => \'prop_rooms\',
\'value\' => $rooms,
\'compare\' => \'=\'
),
),
);
};
我确信我的wp\\U查询是错误的,请帮助我或给我指一篇可以帮助我解决这个问题的文章。
**
更新-我最终做了什么:
**
我按照tony的建议检查了每个变量,然后更改了compare
根据变量结果登录每个查询。
知道这一点compare => \'=\'
返回与该值相等的所有值。compare => \'!=\'
将返回不等于该值的所有内容。
这是我最终使用的代码:
$city = $_GET[\'field_59ae96d970a06\']; //prop_city
$type = $_GET[\'field_59ec7533be002\']; //prop_type
$rooms = $_GET[\'field_59ae9e2370a0b\'];
//check for each var if returns empty value or not
if($city == ""){
$city_val = "!=";
}else{
$city_val = "=";
};
if($type == "all types"){
$type_val = "!=";
}else{
$type_val = "=";
};
if($rooms == "all rooms"){
$rooms_val = "!=";
}else{
$rooms_val = "=";
};
//the query:
if (isset($_GET[\'front-side-prop-search\'])){
$args = array(
\'posts_per_page\' => 9,
\'post_type\' => \'property\',
\'meta_query\' => array(
\'relation \' => \'AND\',
array(
\'key\' => \'prop_city\',
\'value\' => $city,
\'compare\' => $city_val,
),
array(
\'key\' => \'prop_type\',
\'value\' => $type,
\'compare\' => $type_val,
),
array(
\'key\' => \'prop_rooms\',
\'value\' => $rooms,
\'compare\' => $rooms_val,
),
),
);
};
最合适的回答,由SO网友:Tony M 整理而成
下面的例子只是改变了args
基于您的3个输入字段。这样就无需检查这些值(并使用“all”来value
). 我相信一些逻辑运算符的组合compare
和relation
可以做这项工作,但这也行。
if (isset($_GET[\'front-side-prop-search\'])){
// test whether $city has a selected value, if so then args below:
// $city and $type selected
$args = array(
\'posts_per_page\' => 9,
\'post_type\' => \'property\',
\'meta_query\' => array(
\'relation \' => \'AND\',
array(
\'key\' => \'prop_city\',
\'value\' => $city,
\'compare\' => \'=\',
\'meta_query\' => array(
\'relation \' => \'OR\',
array(
\'key\' => \'prop_city\',
\'value\' => \'All\',
\'compare\' => \'NOT LIKE\',
),
),
),
array(
\'key\' => \'prop_type\',
\'value\' => $type,
\'compare\' => \'=\'
)
),
);
// $city and $rooms
$args = array(
\'posts_per_page\' => 9,
\'post_type\' => \'property\',
\'meta_query\' => array(
\'relation \' => \'AND\',
array(
\'key\' => \'prop_city\',
\'value\' => $city,
\'compare\' => \'=\',
\'meta_query\' => array(
\'relation \' => \'OR\',
array(
\'key\' => \'prop_city\',
\'value\' => \'All\',
\'compare\' => \'NOT LIKE\',
),
),
),
array(
\'key\' => \'prop_rooms\',
\'value\' => $rooms,
\'compare\' => \'=\'
),
),
);
// etc
};