0

I'm trying to display posts of an author by id OR those posts which have a meta value as author ID.

I have a custom field in the posts section as Additional Author (additional_author) and now I want to query the posts accordingly.

Currently, I'm using these query args.

$actual_posts_args = array(
    'posts_per_page' => 10,
    'author' => 2,
);

And it displays the posts of author 2 perfectly.

But when I use meta_query with this one, it ignores it.

$actual_posts_args = array(
    'posts_per_page' => 5,
    'author' => 2,
    'meta_query' => array(
        array(
            'key'     => 'additional_author',
            'value'   => 2,
            'compare' => 'LIKE',
        ),
    ),
);

And if I use the remove author arg, it displays posts by meta_query perfectly.

Is there any way to display both of the posts?

1 Answer 1

0

The main problem is the AND logic that wordpress uses when creating a sql query.

This query will look for posts that have both author = 2 and meta query, additional_author that is LIKE 2.

Your best bet is to create your own query to achive this result.

I have created a static query for you to try

global $wpdb;

$sql  = 'SELECT *';
$sql .= " FROM {$wpdb->prefix}posts AS p";
$sql .= " JOIN {$wpdb->prefix}postmeta AS pm ON p.ID = pm.post_id";
$sql .= ' WHERE (p.post_author = 2';
$sql .= ' OR (pm.meta_key = \'additional_author\' AND pm.meta_value LIKE \'%2%\'))';
$sql .= ' AND p.post_type = \'post\'';
$sql .= ' AND p.post_status = \'publish\'';
$sql .= ' GROUP BY p.ID';
$sql .= ' ORDER BY p.post_date DESC';
$sql .= ' LIMIT 5';

$results = $wpdb->get_results($sql);

print_r($results);

This is almost an exact copy of the query WordPress has built but with a small change, OR instead of AND.

Its a bit resource pricy because OR logic will create two tables to search in but it will do the work.

We don't have to use $wpdb->prepare because all the sql is hardcoded by us, if you would like this query to be dynamic let me know and ill update the answer.

2
  • Any other way to do it without writing a custom DB query? Aug 18, 2021 at 5:02
  • @RameezIqbal Not for the OR logic, at least not that I know of. But as I said this sql query is just a copy of the excat query that you have in $actual_posts_args, just switch one logic, from AND to OR Aug 18, 2021 at 5:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.