根据1个或多个元值的精确匹配获取单个帖子ID

时间:2013-07-24 作者:Andrew

我想根据元值的精确匹配(可能大于1)来查找帖子ID。我找到的所有示例都显示了从1个meta值中查找post ID。

在我的示例中,我想传入一个值数组并找到一个精确匹配。下面是我到目前为止所拥有的,它可以找到正确的帖子ID,但并不完全匹配。如果any 在下面的数组中匹配个值。我需要匹配all 的值。

// these values are dynamic, so multiple meta_query arrays are not an option
$array_of_values_to_match = array( \'1\', \'2\', \'3\' );

$args = array(
    \'post_type\' => \'post\',
    \'meta_query\' => array(
        array(
            \'key\' => \'_some_meta_key\', // they all have the same meta_key
            \'value\' => $array_of_values_to_match,
            \'compare\' => \'IN\' // can\'t use = when passing in an array
        ),
    ),
);

$posts = get_posts( $args );
根据法典,Array support is limited to a compare value of \'IN\', \'NOT IN\', \'BETWEEN\', or \'NOT BETWEEN\'

因此,如果我的wp\\u postmeta表如下所示,它应该将post列表与122

post_id   meta_key          meta_value
122       _some_meta_key    1
122       _some_meta_key    2
122       _some_meta_key    3
但是not 如果它看起来像这样(没有3)

post_id   meta_key          meta_value
122       _some_meta_key    1
122       _some_meta_key    2
122       _some_meta_key    8

1 个回复
最合适的回答,由SO网友:Milo 整理而成

如果要将它们全部匹配,则必须添加\'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 );

结束

相关推荐