user-access-manager icon indicating copy to clipboard operation
user-access-manager copied to clipboard

Ability to set access programatically

Open treetrum opened this issue 8 years ago • 2 comments

Is there a way to set the access with a filter/hook when a post is saved? I would love to be able to setup some conditional logic in my PHP to set the access for a post when it is created by specific users.

Alternatively, is there a way to set the access to automatically be set the authors access group?

treetrum avatar Oct 24 '17 23:10 treetrum

Ok, I think I worked this out.

I've used the following code in my functions.php file to automatically set the posts access to the authors usergroups when the post is saved.

function set_post_access_to_author_usergroup() {

    global $userAccessManager;

    if (isset($userAccessManager)) {
        $uamAccessHandler = $userAccessManager->getAccessHandler();
        $userGroupsForUser = $uamAccessHandler->getUserGroupsForObject(\UserAccessManager\Object\ObjectHandler::GENERAL_USER_OBJECT_TYPE, get_current_user_id());

        $postId = get_the_id();
        $postType = get_post_type();

        foreach ($userGroupsForUser as $groupId => $userGroup) {
            $userGroup->addObject($postType, $postId);
            $userGroup->save();
        }
    }
}

// Must use a priority of > 10 to ensure this runs after UAM
add_action( 'save_post', 'set_post_access_to_author_usergroup', 11, 0);

Obviously this could be very incorrect - I scoured through the source code to work this out. Let me know if there's a better way of doing this 😄 If not, feel free to close this issue.

Otherwise, hopefully this can help someone else.

treetrum avatar Nov 24 '17 00:11 treetrum

Here is the updated snippet for compatibility with 2.1.7, tested up to 2.1.10

function set_post_access_to_author_usergroup() {

    global $userAccessManager;

    if (isset($userAccessManager)) {
        $uamUserGroupManager = $userAccessManager->getUserGroupHandler();
        $userGroupsForUser = $uamUserGroupManager->getUserGroupsForObject(\UserAccessManager\Object\ObjectHandler::GENERAL_USER_OBJECT_TYPE, get_current_user_id());

        $postId = get_the_id();
        $postType = get_post_type();

        foreach ($userGroupsForUser as $groupId => $userGroup) {
            $userGroup->addObject($postType, $postId);
            $userGroup->save();
        }
    }
}

// Must use a priority of > 10 to ensure this runs after UAM
add_action( 'save_post', 'set_post_access_to_author_usergroup', 11, 0);

treetrum avatar Jan 19 '18 00:01 treetrum