4

I am trying to give my "authors" (who I have renamed "captains") the ability to access the user profile of their team members and only their team members. The teams are defined by a user-meta box (this works better than a user taxonomy for the rest of the project). Authors have been given the edit_users capability.

I was thinking I could do something like this:

add_action('user_row_actions','captains_user_row_actions',10,2);

function captains_user_row_actions($actions, $user_object) {  // remove the ability to edit a non-team-member
$current_user = wp_get_current_user();
$cap_team_id = get_user_meta($current_user->ID, 'team-meta', true);
$user_team_id = get_user_meta($user_object->ID, 'team-meta', true);    

global $pagenow;
if ($pagenow=='users.php' && isset($user_object->caps['author']) &&  $cap_team_id != $user_team_id )
unset($actions['edit']);

return $actions;
}

Either this is not the way to go. Or I'm missing something.

1

I did not test the following code, but it should do what you want (or point you in the right direction, at least).

function captains_user_row_actions($actions, $user) {
    // remove the ability to edit a non-team-member
    $cap_team_id = get_user_meta(wp_get_current_user()->ID, 'team-meta', true);
    $user_team_id = get_user_meta($user->ID, 'team-meta', true);
    if ('users.php' === $GLOBALS['pagenow'] && $cap_team_id !== $user_team_id)
        unset($actions['edit']);

    return $actions;
}
add_action('user_row_actions', 'captains_user_row_actions', 10, 2);

// EDIT
Add the following to your functions.php file to also handle direct editing:

function my_captain_func() {
    $cap_team_id = get_user_meta(wp_get_current_user()->ID, 'team-meta', true);
    $user_team_id = get_user_meta($_GET['user_id'], 'team-meta', true);
    if ($cap_team_id !== $user_team_id && ! current_user_can('edit_pages')) {
        wp_redirect(admin_url());   // or wherever you like
        exit;
    }
}   
if ('user-edit.php' === $GLOBALS['pagenow'])
    add_action('wp_loaded', 'my_captain_func');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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