我正在使用WP\\u Query按用户输入对帖子进行排序。输入包含元值,该值显示在选择类型字段中。
通常,当表单中插入值时,wp\\u查询工作正常。但是,如果用户希望对所有帖子进行排序,而不管meta值是什么,那又如何呢?
我的意思是:
//this is my input form
<select name"rating">
<option value="">Show all</option> //if user select this, show all post, regardless the rating
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
//here is for WP_Query
$args = array(
\'post_type\'=>array(\'listing\',\'renting\'),
\'posts_per_page\'=> 6,
\'order\' => \'DESC\',
\'meta_query\' => array(
\'relation\' => \'AND\',
array(
\'key\' => \'rating\',
\'value\' => $_GET[\'rating\']//here is what I don\'t understand, what if no value in this field?is it take the value as "0"?
),
......
),
正如您所看到的,在select表单中,有一个选项将显示所有帖子,无论评分如何。我该怎么做呢?
谢谢
最合适的回答,由SO网友:pcarvalho 整理而成
检查$GET[\'rating\']是否已设置(isset($\\u GET[\'rating])或是否有任何值。(!empty($\\u GET[\'rating])
如果不是,则生成不带“meta\\u query”的查询fecthing all post
例如:
if ( (isset($_GET[\'rating\']) && !empty($_GET[\'rating\']) ) {
// restrict
$meta[] = array((
\'key\' => \'rating\',
\'value\' => $_GET[\'rating\'] );
}
if ( (isset($_GET[\'tax\']) && !empty($_GET[\'tax\']) ) {
$meta[] = array((
\'key\' => \'tax\',
\'value\' => $_GET[\'tax\'] );
}
$args = array(
\'post_type\'=>array(\'listing\',\'renting\'),
\'posts_per_page\'=> 6,
\'order\' => \'DESC\',
\'meta_query\' => array( \'relation\' => \'AND\', $meta )
);
警告:我没有测试新代码,所以
meta_query
如果$meta为空,则行可能会打断查询。