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

7gs2gvoe  于 2022-12-11  发布在  WordPress
关注(0)|答案(4)|浏览(196)

下面的代码:

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

但是我无法获取没有设置custorder值的帖子。我怎么才能同时检索这些帖子呢?

jobtbby3

jobtbby31#

您可以使用适当的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'
        ]
    ]
];
pobjuy32

pobjuy322#

我不知道这是否是最佳解决方案,但我找到了一个变通方法

$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'

hgc7kmma

hgc7kmma3#

因此,要查找epost类型的帖子,该帖子没有分配关键字为custorder的 meta字段:

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

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

    $query = new WP_Query( $args );
nuypyhwy

nuypyhwy4#

请尝试以下操作:

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

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

相关问题