WP_QUERY WITH多元字段筛选?

时间:2015-03-17 作者:Sonali Kapoor

我有以下查询,但它仍然返回结果,其中包括元值为“deal”的帖子。

我在这件事上遗漏了什么线索

    $args = array(
    \'post_type\' => POST_TYPE,
    \'meta_key\' => \'is_hot\',
    \'meta_value\' => \'1\',
    \'meta_compare\' => \'=\',
    \'posts_per_page\' => 20,
    \'no_found_rows\' => true,
    \'suppress_filters\' => false,
    \'meta_key\'     => \'offer_type\',
    \'meta_value\'   => \'deal\',
    \'meta_compare\' => \'NOT LIKE\',
     ),

);

new WP_Query( $args );

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

不能使用查询多个元字段meta_keymeta_value 参数,您必须使用meta_query 参数使用多个meta_keymeta_value 参数将只使用第一个找到的对,这就是为什么在代码中忽略“offer\\u type NOT LIKE deal”的条件。

因此,正确的查询应该是:

$args = array(

    \'post_type\'        => POST_TYPE,
    \'posts_per_page\'   => 20,
    \'no_found_rows\'    => true,
    \'suppress_filters\' => false,
    //Se the meta query
    \'meta_query\'       => array(
        //comparison between the inner meta fields conditionals
        \'relation\'    => \'AND\',
        //meta field condition one
        array(
            \'key\'          => \'is_hot\',
            \'value\'        => \'1\',
            \'compare\'      => \'=\',
        ),
        //meta field condition one
        array(
            \'key\'          => \'offer_type\',
            \'value\'        => \'deal\',
            //I think you really want != instead of NOT LIKE, fix me if I\'m wrong
            //\'compare\'      => \'NOT LIKE\',
            \'compare\'      => \'!=\',
        )
    ),

);

$query = new WP_Query( $args );

SO网友:grandcoder

meta_compare 可能的值为

“!=”、“>”、“>=”、\'<;\',或=\'。默认值为“=”

如果要使用NOT LIKE 您需要创建meta\\u查询。

实例

\'meta_query\' => array(                  //(array) - Custom field parameters (available with Version 3.1).
   array(
     \'key\' => \'color\',                  //(string) - Custom field key.
     \'value\' => \'blue\'                  //(string/array) - Custom field value (Note: Array support is limited to a compare value of \'IN\', \'NOT IN\', \'BETWEEN\', or \'NOT BETWEEN\')
     \'type\' => \'CHAR\',                  //(string) - Custom field type. Possible values are \'NUMERIC\', \'BINARY\', \'CHAR\', \'DATE\', \'DATETIME\', \'DECIMAL\', \'SIGNED\', \'TIME\', \'UNSIGNED\'. Default value is \'CHAR\'.
     \'compare\' => \'=\'                   //(string) - Operator to test. Possible values are \'=\', \'!=\', \'>\', \'>=\', \'<\', \'<=\', \'LIKE\', \'NOT LIKE\', \'IN\', \'NOT IN\', \'BETWEEN\', \'NOT BETWEEN\'. Default value is \'=\'.
   ),
   array(
     \'key\' => \'price\',
     \'value\' => array( 1,200 ),
     \'compare\' => \'NOT LIKE\'
   ))

结束

相关推荐

使用新的WP-Query()从循环中过滤后期格式;

嗨,我目前正在为我的博客构建一个主题。下面的代码指向最新的帖子(特色帖子)。因为这将有一个不同的风格比所有其他职位。然而我想过滤掉帖子格式:链接使用我在循环中定义的WP查询,因为它给我带来了更多的灵活性。我该怎么做呢? <?php $featured = new WP_Query(); $featured->query(\'showposts=1\'); ?> <?php while ($featured->have_post