I’m assigning some posts to some users whom are not the author of those posts. Typically private posts are visible only to the post authors. So, if the author has 3 posts, on his logged in edit.php
they will get 3 posts. But if another post is assigned to them by custom field (not as a post author), how can I add the post to the post list table?
What I tried so far is: making a function (custom_get_assigned_posts()
) to retrieve all the posts that are assigned to a user_id as an array. But then found that there’s no easy way including post IDs into the existing query:
function add_assigned_posts( $query ) {
if( is_admin() && in_array( $query->get('post_type'), array('mycpt') ) ) {
global $current_user;
$query->set('post__in', custom_get_assigned_posts( $current_user->ID ) );
}
return $query;
}
add_filter( 'pre_get_posts', 'add_assigned_posts' );
But post__in
doesn’t additionally include things, it actually specified posts to retrieve.
How can I include posts that are assigned to a non-author of posts, and are assigned by postmeta?
I think you should be able to do this with the user_has_cap
filter.
Because that filter passes through the post ID in the $args
for the edit_post
capability, you can use that to check if the current user has been artificially given this capability – and if so, force the edit_post
capability to be true for that instance.
Building from the example in the docs linked above, you’d be looking at something like this:
add_filter( 'user_has_cap', 'wpse_227418_edit_extra_posts', 10, 3 );
function wpse_227418_edit_extra_posts($allcaps, $cap, $args){
if($args[0] != "edit_post"){
return $allcaps; // bail out, we're not talking about editing a post here
}
if(get_post_meta($args[2], "additional_author", true) == $args[1]){
// get the meta key 'additional author', checking that it matches the User ID we're looking at the capabilities for
$allcaps[$cap[0]] = true; // make sure edit_posts is true for this author and this post ID
}
return $allcaps;
}
This is pretty quickly put together and is untested so you’d certainly want to test and modify to your needs, but I think this will get you what you want. Of course, adjust the meta_key referred to above to match the key you’re after.
References:
- user_has_cap filter on Codex
- has_cap() function in WP_User class (the function that calls the above filter)