I have a custom taxonomy called coauthor
. On the edit.php
screen, I am trying filter and only show posts authored by the current user OR posts coauthored by the current user. I can get the posts authored by the current user:
function get_authored_posts($query) {
global $user_ID;
$query->set('author', $user_ID);
return $query;
}
add_filter('pre_get_posts', 'get_authored_posts');
I can also get the posts coauthored by the current user:
function get_coauthored_posts($query) {
global $user_ID;
$user = get_userdata($user_ID);
$query->set('taxonomy', 'coauthor');
$query->set('term', $user->user_login);
return $query;
}
add_filter('pre_get_posts', 'get_coauthored_posts');
I believe the results yield posts authored AND coauthored by the current user. I am looking for posts authored OR coauthored by the current user. I am expecting the results from the first and the results from the second to be displayed.
Note: To clarify, coauthors are stored as terms as part of the coauthor
taxonomy. The term is the user_login value.
== EDIT ==
I am currently storing the author as a coauthor. I feel like this is a “work around” for a better solution. How/Can I use a direct query (ignoring the WP_Query object) and return that from the pre_get_posts filter?
When I implemented something similar for a company that needed multiple authors, we did much the same with an author taxonomy. But in that case, we didn’t use the original author field at all.
Basically, it’s not possible to create a standard WP_Query with author=X OR coauthor=Y using standard methods. You’d have to resort to direct SQL fiddling, which is problematic and prone to accidental breakage.
Using the coauthor taxonomy exclusively, however, it’s fairly trivial to make a tax_query which has coauthor IN (X,Y) very simply.
So no, it’s not really a workaround, it’s actually the best way to do it. The posts table is entirely geared towards a single author. If you need multiple authors, then special-casing one of them into that post_author field is actually the real WTF here, because why bother? It’s more sensible to use the taxonomy instead and allow a fully multi-connected coauthor system.
I am not sure if you can easily add OR queries to the $query object.
It seems possible when querying on meta info, eg:
Note the ‘relation’ parameter. This is taken from towards the bottom of this codex page: http://codex.wordpress.org/Class_Reference/WP_Query
An alternative would be to store the author as a coauthor as well.