DEV Community


Posted on

WordPress: modify user capabilities dynamically with functions.php

WordPress provides variety of user roles and capabilities.

It is able to modify user capabilities with functions.php dynamically. 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_cap() {
    // get user
    $user = new WP_User( <user-ID> );
    //$user = new WP_User( '<user-login-name>' );
    //$user = wp_get_current_user();

    // modify capabilities  
    // for example, those to manage users
    $user->add_cap( 'list_users' );
    $user->add_cap( 'edit_users' );
    $user->add_cap( 'create_users' );
    $user->add_cap( 'delete_users' );
// register action
add_action( 'admin_init', 'custom_user_cap' );
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 capabilities to manage users even if they is just a reader or an editor.

Wordpress user capabilities list is here.

Top comments (0)