如何显示缺少元值的帖子

时间:2011-06-28 作者:dwenaus

如何构建查询来查找不包含特定元键或元值的帖子?

例如:

query_posts( array( 
    \'meta_query\' => array(
        array( \'key\' => \'feature\', \'value\' => \'_wp_zero_value\', \'compare\' => \'!=\' )         )
) );

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

由于数据库设计和SQL连接的性质,在没有特定meta键的情况下获取帖子有点棘手。

好吧,最有效的方法是实际获取具有元键的帖子ID,然后将其从查询中排除。

// get all post IDs that *have* \'meta_key\' with a non-empty value
$posts = $wpdb->get_col( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = \'my_key\' AND meta_value != \'\'" );

// get all posts *excluding* the ones we just found
query_posts( array( \'post__not_in\' => $posts ) );

SO网友:Alupotha

$args = array(
    \'meta_query\' => array(
        \'relation\' => \'OR\', //default AND
        array(
            \'key\' => \'feature\',
            \'compare\' => \'NOT EXISTS\'
        ),
        array(
            \'key\' => \'feature\',
            \'value\' => \'_wp_zero_value\',
            \'compare\' => \'=\'
        )
    ));

$the_query = new WP_Query($args);
var_dump($the_query);
进一步阅读:Wordpress Doc

注:在wordpress 3.9之前bug 这就是解决方法

array(
       \'key\' => \'feature\',
       \'compare\' => \'NOT EXISTS\',
       \'value\' => \'\' //add this empty value check for check NOT EXISTS
      ),

结束

相关推荐