Search code examples
phpwordpressroles

How to add capabilities to WP_Role when it cannot be converted to string


I am receiving this error when trying to add new capabilities to two of my user roles:

Error: Object of class WP_Role could not be converted to string ... on line 67

The capability I am trying to add will allow the user to see a custom page that we have built in our WP setup. This is the code I have written to populate the roles:

public static function add_csv_capability():void {
        $rolesToPopulate = array((get_role( 'administrator' )), (get_role( 'editor' )));
        $roles = array_fill_keys(($rolesToPopulate),NULL);
        echo $roles;
        
        foreach ($roles as $role) {
            if ($role) {
                $role->add_cap('use_csv_uploader');
            }
        }
    }

Someone asked if this would answer my question, and it does and it doesn't. It explains what the error is, but now that I know what the error is all about, I need to figure out how to get this code to do what I want, which is to allow me to add capabilities to more than one role.

Any help you can give would be greatly appreciated.

Thanks!


Solution

  • First, create an array of role names and then use array_fill_keys() to create an associative array with these role names as keys and null as values. You then loop through this array and retrieve the corresponding WP_Role object using get_role() and then add the capability to that role.

    So you can use an array of role names instead of an array of WP_Role objects, like this

    public static function add_csv_capability():void {
        $rolesToPopulate = array('administrator', 'editor');
        $roles = array_fill_keys($rolesToPopulate, NULL);
        
        foreach ($roles as $role) {
            if ($role) {
                $role_obj = get_role($role);
                $role_obj->add_cap('use_csv_uploader');
            }
        }
    }
    

    I hope this helps you fix the issue you are facing.