0

Rewritten: Hopefully this helps others. The question wasn't a duplicate question. The custom roles and subscriber account were not being written. It turns out that the if statement after the internal foreach was stopping the writing of the custom roles. Once removed then the loop worked properly.

It's very important for novices to be provided explanations. In this case, I would like to know why the if statement blocked the writing of the custom roles.

if ( $wp_roles->get_role( $role_name )->has_cap( $new_cap ) )


Original statements (bold unique parts to question):

This is frustrating me. After months of trying different ways to think about retrieving all of the default and custom roles, I believed the following code would work. However, it is only returning 4 of the 5 default roles and none of the custom roles. This code works to return administrator, editor, author, and contributor but not subscriber.

I can write an elseif statement after the inner foreach loop and force subscriber to be written as well as an elseif statement to force a known custom role .. but that defeats the purpose of a foreach to return all roles.

Sorry but I'm a complete novice trying to read and understand as much as possible. This means I'm not asking you to write the code but maybe point me in the direction as well as provide an explanation.

        global $current_user, $wp_roles;

    $all_roles = $wp_roles->roles;

    $editable_roles = apply_filters( 'editable_roles', $all_roles );

    foreach ( $editable_roles as $role_name => $role_info ) {

        /** If you have changed the wp_ prefix then you must modify this line to match the new prefix */
        if ( is_object( $current_user ) && isset( $current_user->data->wp_capabilities[ $role_name ] ) ) {

            foreach ( $new_caps as $new_cap ) {
                if ( $wp_roles->get_role( $role_name )->has_cap( $new_cap ) ) {
                    $capabilities[ $new_cap ] = true;
                    $current_user->add_role( $role_name );

                }
            }

        }

    }
  • This is NOT a duplicate because you will see that I specify code which does NOT return all and there is a question which asks for an explanation why subscriber is not returned. – LPH May 24 '14 at 22:59
  • As stated this isn't a duplicate. It turns out the if statement after the internal foreach was stopping all custom roles and subscriber to be written to database. Once removed the if statement then all roles are written properly. – LPH May 26 '14 at 1:33

Your Answer

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

Browse other questions tagged or ask your own question.