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

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.