Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[WordPress] Programmatically Set the WordPress User Role
<?php
/**
* Sets the role for the user as specified in the function.
*
* @param int $user_id The ID of the user for whom we're updating the role.
*/
public function set_user_role( $user_id ) {
// Define a user role based on its index in the array.
$roles = array(
'administrator',
'editor',
'author',
'contributor',
'subscriber'
);
$role = $roles[2];
// Set the user's role (and implicitly remove the previous role).
$user = new \WP_User( $user_id );
$user->set_role( $role );
}
@JamesJosephFinn

This comment has been minimized.

Copy link

JamesJosephFinn commented Oct 8, 2019

Hi @tommcfarlin, I landed here from this blog post of yours. Is there a code example you can point me to which will execute this function when the user submits a post? Much appreciated!

@tommcfarlin

This comment has been minimized.

Copy link
Owner Author

tommcfarlin commented Oct 9, 2019

Hi @tommcfarlin, I landed here from this blog post of yours. Is there a code example you can point me to which will execute this function when the user submits a post? Much appreciated!

If you attach this function to the save_post hook and are able to get the current user ID during that function (usually something like get_current_user_id()[0] should work, then you should be able to use this function.

[0] https://developer.wordpress.org/reference/functions/get_current_user_id/

@JamesJosephFinn

This comment has been minimized.

Copy link

JamesJosephFinn commented Oct 30, 2019

Very helpful. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.