WP获取没有自定义字段值的帖子

时间:2016-06-06 12:31:47

标签: wordpress

我有以下代码:

$args = array(
    'post_type' => 'epost',
    'post_status' => 'future,publish',
    'meta_key' => 'custorder',
    'orderby'=>'meta_value',
    'order' => 'asc',
    'posts_per_page' => 900
);

但我无法获取未设置custorder值的帖子。我怎样才能检索这些帖子?

3 个答案:

答案 0 :(得分:1)

您可以使用正确的meta_query

在一个查询中执行此操作
$args = [
    'post_type'      => 'epost',
    'post_status'    => ['future','publish'],
    'meta_key'       => 'custorder',
    'orderby'        => 'meta_value',
    'order'          => 'ASC',
    'posts_per_page' => 900,
    'meta_query'     => [
        [
            'key'     => 'custorder',
            'compare' => 'EXIST'
        ],
        [    
            'key'     => 'custorder',
            'compare' => 'NOT EXISTS'
        ]
    ]
];

答案 1 :(得分:0)

我不知道是否是最佳解决方案,但我找到了解决方法

$query1 = new WP_Query($args1);
$query2 = new WP_Query($args2);
$the_query = new WP_Query();
$the_query->posts = array_merge( $query1->posts, $query2->posts );
$the_query->post_count = $query1->post_count + $query2->post_count;

将两个不同的参数匹配到一个查询中。对于我使用过'meta_key'=>'custorder'的第一组参数,对于第二组,我添加了'meta_compare'=>'NOT EXISTS'

答案 2 :(得分:-2)

尝试这样的事情:

'meta_query' => array(
          array(
            'key' => 'custorder',
            'value' => '',
            'compare' => '='
            )
          ),

来源:https://codex.wordpress.org/Class_Reference/WP_Meta_Query