Overwriting WordPress core, plugin and theme translations

May 30, 2019

WordPress uses gettext to make the core, plugins and themes translateable. The WordPress core have been translated into many languages and many plugins and themes do have some pre-existing translations too, thanks to many volunteers and companies who have been using their precious time and revenue to save us a lot of time and effort.

But not everybody speaks or writes the same way and because of that you might find yourself wanting to overwrite some or all of the ready made translations. Luckily there are several filters in WordPress that allows you to do that easily.

These are your options:

The “I need to overwrite one or few translations” option

Use gettext filter.

<?php

function wpa_overwrite_translation( $translated, $original, $textdomain ) {
	// For plugins and themes check for textdomain
	if( 'textdomain_here' === $textdomain ) {
		if( 'Exact text you wish to overwrite in plugin or theme' == $translated ) {
			$translated = 'New text';
		}
	}

	// For WordPress core just omit the textdomain check
	if( 'Exact text you wish to overwrite in WordPress core' == $translated ) {
		$translated = 'New text';
	}

	return $translated;
}

add_filter( 'gettext', 'wpa_overwrite_translation', 10, 3 );

If you need context with translations, use gettext_with_context filter.

If you need to translate plural translations, use use ngettext or ngettext_with_context.

The “I’d like to overwrite the whole translation file” option

Use load_textdomain_mofile filter.

For single file:

<?php

function wpa_load_custom_translation_file( $mofile, $domain ) {
	if ( 'textdomain_here' === $domain ) {
		if( 'es_ES' === get_locale() ) {
			$mofile = WP_LANG_DIR . '/custom/textdomain_here-' . get_locale() . '.mo';
		}
	}
	
	return $mofile;
}

add_filter( 'load_textdomain_mofile', 'wpa_load_custom_translation_file', 10, 2 );

Then just place your translation file into:

wp-content/languages/custom/textdomain_here-es_ES.mo

and you should be good to go.

You can find more information on how to edit a translation file from this tutorial.

Comments

avatar
  Subscribe  
Notify of