Wordpress - How to auto-translate custom user roles?
The translate_user_role
function is just a wrapper for translate_with_gettext_context
, defining the context 'User role'.
In this last function, there is the filter hook gettext_with_context
, which provides the context as well as the currently used domain.
So we could do this:
function wpdev_141551_translate_user_roles( $translations, $text, $context, $domain ) {
$plugin_domain = 'plugin-text-domain';
$roles = array(
'Someone',
'Nobody',
// ...
);
if (
$context === 'User role'
&& in_array( $text, $roles )
&& $domain !== $plugin_domain
) {
return translate_with_gettext_context( $text, $context, $plugin_domain );
}
return $translations;
}
add_filter( 'gettext_with_context', 'wpdev_141551_translate_user_roles', 10, 4 );
In order to make this work, we have to do a dummy gettext call, like so:
_x( 'Someone', 'User role', 'plugin-text-domain' );
We could just put this right after add_role
.
This works, but it doesn't seem to be an efficient approach as every gettext call with a context has to pass our function(s).