DEV Community

nabbisen
nabbisen

Posted on

WordPress: modify user roles dynamically with functions.php

WordPress provides variety of user roles and capabilities.

It is able to modify user roles with functions.php dynamically as well as capabilities.

In other words, in terms of security, it is able to act as administrator when there is a way to edit functions.php such as FTP.

Here is a code example.

# functions.php
function custom_user_role() {
    // get user
    $user = new WP_User( <user-ID> );
    //$user = new WP_User( '<user-login-name>' );
    //$user = wp_get_current_user();

    // modify roles 
    // for example, set/unset them as administrator
    $user->add_role( 'administrator' );
    //$user->remove_role( 'administrator' );
}
// register action
add_action( 'admin_init', 'custom_user_role' );
Enter fullscreen mode Exit fullscreen mode

Adding it to functions.php gives the user, which is got by ID, login name or login information, the role as editor even if they is just a reader or a editor.

Wordpress user roles list is here.

Top comments (0)