WP查询:如何从特定作者或具有特定元值的作者获取帖子

时间:2018-04-10 14:31:37

标签: wordpress

我想检索作者(帖子表字段)是给定的那些帖子或具有给定元值的帖子(postmeda表字段)。

如果"作者"是一个元值,我知道我可以使用meta_query来实现它。这里的事情是它不是......所以我认为我不能使用"作者" meta_query中的字段并使用"关系"键。

我正在寻找类似的东西:

$args = array(
    'post_type'  => array('post'),
    'orderby'    => 'ASC',
    'order'      => 'date',
    'meta_query' => array(
        'relation' => 'OR',
        array(
            'relation'    => 'AND',
            array(
                'field'   => 'author',
                'value'   => $author_id,
                'compare' => '==',
            ),
            array(
                'key'     => '_meta_field_name',
                'compare' => 'NOT EXISTS',
            ),
        ),
        array(
            'relation'    => 'AND',
            array(
                'key'     => '_meta_field_name',
                'compare' => 'EXISTS',
            ),
            array(
                'key'     => '_meta_field_name',
                'value'   => $meta_field_value,
                'compare' => '==',
            ),
        ),
    ),
);

$data = new WP_Query( $args );

有关如何使用WP_Query实现该目的的任何建议吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

你可能想尝试像这样的方法。我们的想法是查询您要搜索的两个条件,然后将两个查询合并为一个完成的产品。

//Get posts with the author you're looking for
$args1 = array(
    'author_name' => 'testuser', //or 'author' => $author_id or something else
     );
$data1 = get_posts( $args1 );

//Get posts with the meta data you're looking for
$args2 = array(
    'meta_query' => array(
        array(
            'key'     => 'meta_field_name',
            'compare' => 'EXISTS',
        ),
        array(
            'key'     => 'meta_field_name',
            'value'   => $meta_field_value,
            'compare' => '==',
        ),
    ),
);
$data2 = get_posts( $args2 );

//Merge both arrays
$allData = array_merge( $data1, $data2 );

//Get just the IDs of all the posts found, while also dropping any duplicates
$postIDs = array_unique( wp_list_pluck( $allData, 'ID' ) );

//Do a new query with these IDs to get a properly sorted array of post objects
$args3 = array(
    'post__in' => $postIDs,
    'order' => 'ASC',
    'orderby' => 'date',
    );
$finalAnswer = get_posts( $args3 ); //This is your array of post objects. Ta-Da!