我在function.php中使用以下代码循环:
$meta_query[] = array(
'key' => '$key', 'value' => $value, 'compare' => 'IN', );
我试图在循环后添加下一个$ meta_query, 但在比较中添加” <“。当我添加” IN”时, 它可以工作, 但是当我更改为”> =”或”>”时, 则不起作用。
$meta_query[] = array(
'key' => 'price', 'value' => $value, 'compare' => '>=', );
你知道为什么吗?
这是我的完整代码:
// array of filters (field key => field name)
$GLOBALS['my_query_filters'] = array(
'field_1' => 'type', 'field_2' => 'price', 'field_3' => 'type2', 'field_4' => 'city', 'field_5' => 'price_min', 'field_6' => 'price_max', );
function my_pre_get_posts( $query ) {
global $post;
global $wpdb;
$parametry = get_field_objects($post->ID);
if(!is_single() && $post->ID != 2 && $query->get( 'cat' )){
/* start filter*/
$meta_query = $query->get('meta_query');
foreach( $GLOBALS['my_query_filters'] as $key => $name ) {
// continue if not found in url
if( empty($_GET[ $name ]) ) {
continue;
}
// get the value for this filter
// eg: http://www.website.com/events?city=melbourne, sydney
$value = explode(', ', $_GET[ $name ]);
// append meta query
if($name == 'price_min'){
$meta_query[] = array(
'key' => 'price', 'value' => $value, 'compare' => '>=', );
}
elseif($name == 'price_max'){
$meta_query[] = array(
'key' => 'price', 'value' => $value, 'compare' => '<=', );
}
else{
$meta_query[] = array(
'key' => $name, 'value' => $value, 'compare' => 'IN', );
}
}
// update meta query
$query->set('meta_query', $meta_query);
在URL(和表wp_postmeta)中, 我具有:类型, 类型2, 价格和城市。我没有price_min和price_max, 所以我想在price字段上进行操作。
这是过滤后我的工作数组:
Array ( [0] => Array ( [key] => type [value] => Array ( [0] => flat) [compare] => IN ) [1] => Array ( [key] => city[value] => Array ( [0] => Cracow) [compare] => IN ) )
当我添加price_min和price_max时, 这不起作用的数组:
Array ( [0] => Array ( [key] => type [value] => Array ( [0] => flat) [compare] => IN ) [1] => Array ( [key] => city [value] => Array ( [0] => Cracow) [compare] => IN ) [2] => Array ( [key] => price [value] => Array ( [0] => 50000 ) [compare] => >= ) [3] => Array ( [key] => price [value] => Array ( [0] => 300000 ) [compare] => <= ) )
#1
$ value可能不是整数, 因此当它是字符串时尝试将其值比较为整数会引起一些问题。在你的WP_Query参数之前, 将此代码放置在文件中:
$value = (int) $value;
看一看PHP中的杂耍类型以获得更多信息。
这是WP_Query元比较的文档。
来源:
https://www.srcmini02.com/66230.html