我有一个名为course_duration
的自定义字段,即numeric
。
这就是我建立meta_query
的方式:
$duration = $_GET['course_duration'];
$args = array(
'fields' => 'ids',
'post_type' => 'cp_course', 'numberposts' =>-1,'orderby' => 'ID', 'order' => 'ASC', 's' => $searchterm,
'meta_query' =>
array(
'key' => 'course_duration',
'type' =>'numeric',
'compare' => '=',
'value' => $duration,
),
);
$course = get_posts($args);
$duration
成功传递,我可以通过echo对其进行检查,并且$searchterm
为空。这是产生的$args
:
array (size=7)
'fields' => string 'ids' (length=3)
'post_type' => string 'cp_course' (length=9)
'numberposts' => int -1
'orderby' => string 'ID' (length=2)
'order' => string 'ASC' (length=3)
's' => string '' (length=0)
'meta_query' =>
array (size=3)
'key' => string 'course_duration' (length=15)
'type' => string 'numeric' (length=7)
'value' => string '5' (length=1)
但是查询失败。它应该只返回带有duration=5
的课程,但返回所有课程。我在做什么错了?
编辑
即使我尝试使用硬编码的$duration
也不起作用。像这样:
$duration = $_GET['course_duration'];
$args = array(
'fields' => 'ids',
'post_type' => 'cp_course', 'numberposts' =>-1,'orderby' => 'ID', 'order' => 'ASC', 's' => $searchterm,
'meta_query' =>
array(
'key' => 'course_duration',
'type' =>'numeric',
'compare' => '=',
'value' => 15, //Hardcoded
),
);
$course = get_posts($args);
答案 0 :(得分:1)
请使用以下代码:
$duration = $_GET['course_duration'];
$args = array(
'fields' => 'ids',
'post_type' => 'cp_course', 'numberposts' =>-1,'orderby' => 'ID', 'order' => 'ASC', 's' => $searchterm,
'meta_query' =>
array(
array(
'key' => 'course_duration',
'type' =>'numeric',
'value' => intval($duration)
)
),
);
$course = get_posts($args);
答案 1 :(得分:0)
在这里您可以为meta_query设置'compare'=>'='