skip to Main Content

I created a custom user role in WordPress:
add_role('warehouse', 'Warehouse', get_role('administrator')->capabilities);

How to add translations for the role name so that it shows up in admin dashboard in the correct language based on the preferences of the currently logged in admin?

Adding a basic translation function call does not seem to help as add_role function runs once and then fetches the saved role from DB.
add_role('warehouse', __('Warehouse', 'mytextdomain'), get_role('administrator')->capabilities);

2

Answers


  1. Chosen as BEST ANSWER

    WordPress uses the translate_user_role function to render the translated role names. This expects the localized strings to be set in the default translations domain.

    You can override the default translations with the following filter:

    function translate_custom_roles($translation, $text, $context){
        if ($context === 'User role' and $text === 'Role Name')){
            $translation = __('Role Name', 'yourtextdomain');
        }
        return $translation;
    }
    add_filter( 'gettext_with_context_default', 'translate_custom_roles', 10, 3);
    

  2. We can achieve this by using the editable_roles hook of the WordPress, with the help of this hook we can dynamically translate the role name based on the current admin’s language choice.

    We need to add the given code to the functions.php file of the theme.

    function translate_the_role_name( $roles ) {
        if ( isset( $roles['warehouse'] ) ) {
            $roles['warehouse']['name'] = __( 'Warehouse' , 'mytextdomain' );
        }
        return $roles;
    }
    add_filter( 'editable_roles' , 'translate_the_role_name' );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search