Override default WordPress core translation

WordPress is set to Dutch language. When I use get_the_archive_title() my theme correctly outputs "Categorie: Category-name" on a category archive page. However I'd like that to read "Sectie: Category-name".

I do not want to change the Dutch language file in the wp-content/languages folder, because that will be updated by WordPress updates.

I tried copying that translation file, altering the "category" translation and putting the new nl_NL.mo file into my-theme/languages. This did not have any effect.

How can I achieve a different translation for some strings without altering the core translation files?

Topic language translation Wordpress

Category Web


I was about to use the "add_filter( 'gettext'..." solution suggested above but then read at https://developer.wordpress.org/reference/hooks/gettext/ that this solution can have quite a negative performance impact. I suggest to therefore go with alternative solutions where possible. In my case I can copy a theme template file to my child theme and edit the string in the template file. This can be a great solution but it of course doesn't help for strings that don't appear in template files.

PS: I meant to add this as a comment but unfortunately I'm not allowed to do so yet.


It's also possible to use get_the_archive_title filter in your functions.php:

function archive_title_modify( $title ) {
    return str_replace('Categorie: ', 'Sectie: ', $title);
}
add_filter('get_the_archive_title', 'archive_title_modify');

The advantage is that it's called only once per page, instead on every translated string as with gettext filter.


You could use gettext filter:

add_filter( 'gettext', 'cyb_filter_gettext', 10, 3 );
function cyb_filter_gettext( $translated, $original, $domain ) {

    // Use the text string exactly as it is in the translation file
    if ( $translated == "Categorie: %s" ) {
        $translated = "Sectie: %s";
    }

    return $translated;
}

If you need to filter a translation with context, use gettext_with_context filter:

add_filter( 'gettext_with_context', 'cyb_filter_gettext_with_context', 10, 4 );
function cyb_filter_gettext_with_context( $translated, $original, $context, $domain ) {

    // Use the text string exactly as it is in the translation file
    if ( $translated == "Categorie: %s" ) {
        $translated = "Sectie: %s";
    }

    return $translated;
}

A translation with context means that a context is given in the gettext function used to translate the string. For example, this is without context:

$translated = __( 'Search', 'textdomain' );

And this is with context:

$translated = _x( 'Search', 'form placeholder', 'textdomain' );

Similar filters are available for plural translations ([_n()][2] and [_nx()][2]): ngettext and ngettext_with_context.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.