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

问题描述 投票:0回答:4

我有以下代码:

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

但是我无法获取未设置

custorder
值的帖子。我怎样才能检索这些帖子?

php wordpress
4个回答
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'
        ]
    ]
];

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'


0
投票

因此,要查找类型为

epost
且没有分配了键
custorder
的元字段的帖子:

    $metaKey = 'custorder';
    $postType = 'epost';

    $args = [
        'post_type'      => $postType,
        'meta_query'     => [
            [
                'key'     => $metaKey,
                'compare' => 'NOT EXISTS'
            ]
        ]
    ];

    $query = new WP_Query( $args );

-2
投票

尝试这样的事情:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.