Search code examples
wordpresstranslationrolespolylang

Translating a custom user role name in WordPress


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);


Solution

  • 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);