我在functions.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)中我有:type,type2,price和city。我没有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 ) )
当我添加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] => <= ) )
答案 0 :(得分:1)
$value
可能不是一个整数,因此当它是一个字符串时,试图将它的值作为整数进行比较会导致一些问题。在WP_Query
参数之前,请将此代码放在您的文件中:
$value = (int) $value;
在PHP中查看type juggling以获取更多信息。