根据多个元键值计算帖子

时间:2016-04-25 11:15:50

标签: arrays wordpress loops meta-key

我正在尝试计算存在某些元键值的帖子数量,在这种情况下,帖子的键值为'texture'且值为'soft',并且还有一个'color'键为'red' ','蓝色'或'绿色'。

我的代码没有错误,但它似乎计算所有帖子,而不仅仅是具有上述元键值的帖子:

$args = array(
    'posts_per_page'    => -1,
    'post_type'         => 'post',
    'post_status'       => 'publish',
    'author'            => $current_user_id,
    'meta_query' => array(
       'key'   => 'texture',
       'value' => 'soft'
    ),
    array(
       'key'   => 'colours',
       'value' => array('red', 'blue', 'green')
    )
);

$posts_query = new WP_Query($args);
$the_count = $posts_query->post_count;

echo $the_count;

我做错了什么?

干杯。

1 个答案:

答案 0 :(得分:1)

尝试在元数组'relationship' => 'AND'meta_query中添加'compare' => 'IN',其中包含多个值 ('red', 'blue', 'green') ,如下所示:

'meta_query' => array(
    'relationship' => 'AND',
    array(
        'key'   => 'texture',
        'value' => 'soft'
    ),
    array(
        'key'   => 'colours',
        'value' => array('red', 'blue', 'green'),
        'compare' => 'IN'
    )
)

编辑#1:

也许在您的值周围添加%标记可以解决问题,我不是100%确定它会起作用,但您可以尝试一下,就像这样:

'meta_query' => array(
    'relationship' => 'AND',
    array(
        'key'   => 'texture',
        'value' => 'soft'
    ),
    array(
        'key'   => 'colours',
        'value' => array('%red%', '%blue%', '%green%'),
        'compare' => 'IN'
    )
)

我希望它有效,谢谢..

相关问题