Menü schliessen
Created: September 9th 2021
Last updated: December 10th 2021
Categories: Common Web Development,  Php,  Wordpress
Author: Tim Fürer

WordPress: Function for Easily Adding Custom Roles

Tags:  PHP,  wordpress
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

Do you need to add custom WordPress roles? Here's an easy and flexible solution for you.


The Code

This is the code you need. Add it your functions.php:

function custom_roles() {
    global $wp_roles;

    $customRoles = [
        // Add your Custom Roles here
    ];

    if (!empty($customRoles) && get_option('custom_roles_version') !== $customRoles) {
        $all_roles = apply_filters('editable_roles', $wp_roles->roles);
        $defaultRoles = [
            'administrator',
            'editor',
            'author',
            'subscriber',
            'contributor'
        ];

        foreach ($all_roles as $key => $role) {
            if (in_array($key, $defaultRoles)) {
                continue;
            }

            remove_role($key);
        }

        foreach ($customRoles as $singleRole) {
            $roleSlug = $singleRole['slug'];
            $roleDisplay = $singleRole['display'];
            $roleCap = $singleRole['capabilities'];
            $roleInheritCap = $singleRole['inherit_capabilities'];

            if ($roleCap && $roleInheritCap) {
                $roleFinalCap = array_merge(get_role($roleInheritCap)->capabilities, $roleCap);
            }
            elseif ($roleCap) {
                $roleFinalCap = $roleCap;
            }
            elseif ($roleInheritCap) {
                $roleFinalCap = get_role($roleInheritCap)->capabilities;
            }
            else {
                add_role($roleSlug, $roleDisplay);
                continue;
            }

            add_role($roleSlug, $roleDisplay, $roleFinalCap);
        }

        update_option('custom_roles_version', $customRoles);
    }
}
add_action('init', 'custom_roles');

How To Use

Inside the "custom_roles()" function, there's a list called "$customRoles", in which you can define your custom roles.

Expected Structure of "$customRoles"

$customRoles = [ array $role,]

"$customRoles" is a list that expects to contain a single or multiple arrays ("$role"), every one of which represents a custom role.

Each custom role array ("$role") uses the following keys to define their role:

  • "slug": (string) (Required)
    Defines the role's slug.
  • "display": (string) (Required)
    Defines the role's display name.
  • "inherit_capabilities": (string) (Optional)
    Inherits another role's capabilities by their slug.
  • "capabilities": (array) (Optional)
    List that defines the role's capabilities, keyed by capability name; e.g. array("edit_posts" => true, "delete_posts" => false).
    Combines with and overwrites inherited capabilities.

Examples of Proper "$customRoles" Structure

First, this will create a bare minimum custom role:

$customRoles = [
        array(
            'slug' => 'incapable',
            'display' => 'Incapable Role'
        )
    ];

Explanation: The keys "slug" and "display" are required, but the keys "inherit_capabilities" and "capabilities" are optional. This role has no capabilities.

This will create a custom role that has the "read" capability:

$customRoles = [
        array(
            'slug' => 'example3',
            'display' => 'Only Read',
            'capabilities' => array(
                'read' => true
            )
        )
]

Explanation: The key "capabilities" takes an array, the keys of which are relative to capability names. We add the key "read" to "capabilities" and set it to true.

This will create a custom role that has the exact same capabilities as a standard WordPress editor:

$customRoles = [
        array(
            'slug' => 'editor_clone',
            'display' => 'Editor Clone',
            'inherit_capabilities' => 'editor'
        )
]

Explanation: The key "inherit_capabilities" is set to "editor", thus this role will inherit all capabilities of the role that has the slug, "editor".

Finally, this will create a custom role that has similar capabilities like a standard WordPress editor, but differs in that it cannot delete posts:

$customRoles = [
        array(
            'slug' => 'similar_editor_clone',
            'display' => 'Similar Editor Clone',
            'inherit_capabilities' => 'editor',
            'capabilities' => array(
                'delete_posts' => false
            )
        )
]

Explanation: We, again, inherit the capabilities of the role, "editor". Unwantedly, "editor" has the capability "delete_posts" set to true. Luckily for us though, we can use the key "capabilities" to overwrite inherited capabilities' values, as when inherited and manually set capabilities are merged, the manually set ones will have priority over the inherited.