1
votes

I would like to retrieve all those posts whose author (post table field) is a given one OR those which has a given meta value (postmeda table field).

If "author" was a meta value, I know I could use a meta_query to achieve it. The thing here is that it is not... so I think I cannot use the "author" field within a meta_query and use the "relation" key.

I'm looking for something like:

$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 );

Any suggestion on how to achieve that using WP_Query?

Thanks!

1

1 Answers

0
votes

You might like to try an approach like this one instead. The idea is to query the two conditions you want to search for, then merge the two queries into one finished product.

//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!