带有多个meta_values的Wordpress WP_Query,用于meta_key

时间:2016-03-04 14:38:50

标签: php mysql wordpress metadata wp-query

我正在尝试运行WP_Query,以便使用多个元值搜索数据库中的所有产品。

e.g

  • 产品1 - > meta_key ['key1'] - > meta_value ['value1']
  • 产品2 - > meta_key ['key1'] - > meta_value ['value2']
  • 产品3 - > meta_key ['key1'] - > meta_value ['value3']

所以我想得到所有三种产品。我的论点是

$args = array(
        'post_type' => 'product',
        'posts_per_page' => 2,
        'orderby'    => 'title',
        'order'      => 'ASC',
        'meta_query' => array(
            'relation' => 'OR',
            array(
                'key'     => 'key1',
                'value'   => 'val1',
                'compare' => '='
            ),
            array(
                'key'     => 'key1',
                'value'   => 'val2',
                'compare' => '='
            ),
            array(
                'key'     => 'key1',
                'value'   => 'val3',
                'compare' => '='
            ),
        ),
        'paged' => $paged
        );

问题是没有产品退货。相反,如果只给一个meta_key => meta_value对它工作正常

$args = array(
    'post_type' => 'product',
    'posts_per_page' => 2,
    'orderby'    => 'title',
    'order'      => 'ASC',
    'meta_key' => 'key1',
    'meta_value' =>'val1',
    'paged' => $paged
);

1 个答案:

答案 0 :(得分:0)

您应该使用IN作为compare值,如下所示:

$args = array(
    'post_type' => 'product',
    'posts_per_page' => 2,
    'orderby'    => 'title',
    'order'      => 'ASC',
    'meta_query' => array(
        array(
            'key'     => 'key1',
            'value'   => array('val1','val2','val3'),
            'compare' => 'IN',
        ),
    ),
    'paged' => $paged
);

希望它有所帮助!