Displaying WordPress roles in the current language

While writing a WordPress plugin that displays the available user roles, I came across a snag: the user roles that I had fetched from WordPress weren’t translated into the site’s current language.

I’m not quite sure I understand the reasoning behind this since WordPress offers functions to return an array with the actual role as the key, and the display string as the array value, like:

array( 'administrator' => 'Administrator' );

So why can’t WordPress return the “correct” (i18n) language string for the array value … anyway, there’s a solution.

Looking at how WordPress does it under “Settings > General” in the WordPress Admin, I eventually found a call to translate_user_role(), which requires one parameter, the role array name value, e.g. “Administrator”. The function will then return the correct (language context aware) display string.

So to put it into a functional context, it may look something like this:

function i18n_get_wp_roles() {
    $wp_roles = wp_roles();
    if ( is_object( $wp_roles ) ) {
        $roles = array_keys( $wp_roles->roles );
        $role_names = $wp_roles->get_names();
    } else {
        $roles = false;
        $role_names = array();
    }
    $return_roles = array();
    if ( is_array( $roles ) ) {
        foreach( $roles as $role_k => $role_v ) {
            if ( ! empty( $role_names[$role_v] ) ) {
                $return_roles[$role_v] = translate_user_role( $role_names[$role_v] );
            } else {
                $return_roles[$role_v] = 'Unknown role (' . $role_v . ')';
            }
        }
    } else {
        error_log( basename(__FILE__) . ' (' . __FUNCTION__ . '): wp_roles() returned empty' );
    }
    return( $return_roles );
}

 

Leave a Comment

Notify me of followup comments via e-mail. You can also subscribe without commenting.

This site uses Akismet to reduce spam. Learn how your comment data is processed.