2

User A authored and published a post. In that post, User A selected User B as the "Manager" (a custom meta field).

How can I allow User B to edit any post in which they are selected as the "Manager"?

I'm comfortable with code. Looking for a way to programmatically hook into the check for who can edit a post.

1 Answer 1

2

Looking at current_user_can()'s documentation, I see that it uses WP_User::has_cap(). So if your code (or the WP core code) uses something like current_user_can( 'edit_post', $post->ID ) to determine if the current user can edit the current post, you can use the user_has_cap filter (called in WP_User::has_cap()):

add_filter( 'user_has_cap', 'wpse360937_allow_manager', 10, 4 ); function wpse360937_allow_manager( $allcaps, $caps, $args, $user ) { // Bail out if we're not asking about a post: if ( 'edit_post' != $args[0] ) { return $allcaps; } // Bail out for users who can already edit others posts: if ( $allcaps['edit_others_posts'] ) { return $allcaps; } // Bail out if the user is the post author: if ( $args[1] == $post->post_author ) { return $allcaps; } $post_id = $args[2]; $manager_id = get_post_meta( $post_id, 'manager', true ); // Assumes the meta field is called "manager" // and contains the User ID of the manager. if ( $manager_id == $user->ID ) { $allcaps[ $caps[0] ] = true; } return $allcaps; } 

(Code partly based on the User Contributed Notes on the user_has_cap filter docs.)

2
  • Revisiting this because this solution has stopped working for me (actually, I'm doubting now if it ever worked). If anyone sees this and has insight, let me know. The solution in this answer do allow the user to access a post's Edit screen, but upon clicking "Update" the site gives "Sorry, you are not allowed to edit posts as this user." I'm curious if this is the issue: github.com/WordPress/WordPress/blob/master/wp-admin/includes/… Commented Dec 9, 2022 at 23:07
  • Took me a while to track down a fully working solution... here's where we landed: gist.github.com/brandonjp/bf8a2ef3cab014b5ae3dba3e510bca2d Commented Jan 3, 2023 at 5:22

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.