0

I'm trying to write a function that checks if a specific role exists. I found the following code on the web but it doesn't work for me:

function role_exists( $role ) {
    if ( ! empty( $role ) ) {
        return $GLOBALS['wp_roles']->is_role( $role );
    }

    return false;
}

I get the following error message: Fatal error: Uncaught Error: Call to a member function is_role() on null in C:\xampp...

I tried to output $GLOBALS['wp_roles'] with a print_r but it's empty.

What am I missing? Thanks

1
  • 2
    Where are you calling this function? Is there any reason you're avoiding using the is_role() function which WordPress provides?
    – bosco
    Sep 19 at 21:10

2 Answers 2

1

This is based on Bosco's comment. You can do this instead of line 3 in the above code:

wp_roles()->is_role( 'editor' );

That grabs a WP_Roles object (what the code you had tries to do by getting a global variable) and calls the same is_role() function.

1

I'm calling the function below in my file to create a new role:

if ( ! ( role_exists( 'manager' ) ) ) {
    function new_role_manager() {
        global $wp_roles;

        if ( ! isset( $wp_roles ) ) {
            $wp_roles = new WP_Roles();
        }

        $adm = $wp_roles->get_role( 'administrator' );

        $wp_roles->add_role( 'manager', 'Gestionnaire', $adm->capabilities );
    }

    add_action( 'init', 'new_role_manager' );
}

I fixed my problem using Nabha's solution. Here is the updated role_exists() function:

function role_exists( $role ) {
    if ( ! empty( $role ) ) {
        return wp_roles()->is_role( $role );
    }

    return false;
}

Many thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.