如果要将它们全部匹配,则必须添加\'relation\' => \'AND\'
并分别检查每个值:
$args = array(
\'post_type\' => \'post\',
\'meta_query\' => array(
\'relation\' => \'AND\',
array(
\'key\' => \'_some_meta_key\',
\'value\' => 1,
\'compare\' => \'=\'
),
array(
\'key\' => \'_some_meta_key\',
\'value\' => 2,
\'compare\' => \'=\'
),
array(
\'key\' => \'_some_meta_key\',
\'value\' => 3,
\'compare\' => \'=\'
),
),
);
为了避免将其硬编码到查询中,可以动态构建查询参数,以根据数组的内容添加关系和值:
$array_of_values_to_match = array( \'1\', \'2\', \'3\' );
// set some initial args
$args = array(
\'post_type\' => \'post\',
\'meta_query\' => array(),
);
// if there\'s more than 1 value, add the relation arg
if( 1 < count( $array_of_values_to_match ) ){
$args[\'meta_query\'][\'relation\'] = \'AND\';
}
// for each of the array values, add a meta query for that value
foreach( $array_of_values_to_match as $val ){
$args[\'meta_query\'][] = array(
\'key\' => \'_some_meta_key\',
\'value\' => $val,
\'compare\' => \'=\'
);
}
$posts = get_posts( $args );