Skip to content
All writing

Translate any string in WordPress with the gettext filter

Use WordPress's gettext filter to translate or rename any string, even when your translation plugin refuses to cooperate.

#articlesi18nwordpressphp

I've seen it all translating WordPress. WPML, TranslatePress, or any of the (many) other plugins: each one handles translation VERY differently (ahem, MultilingualPress…). Stack enough code and plugins, and some word or sentence will refuse to get along with you.

That was my case: a few strings just wouldn't translate the way I wanted.

Another case: your site is in one language, and you want to change a few words without installing a plugin. Either way, the gettext filter is your friend.

<?php
add_filter( 'gettext', 'translate_strings', 20, 3 );

function translate_strings( $translated, $original, $domain ) {
	if ( $domain === 'woocommerce' ) {
		if ( $original === 'Store' ) {
			$translated = 'Exposition';
		} elseif ( $original === 'General Setting' ) {
			$translated = 'Paramètres';
		}
	}
	return $translated;
}

Adapt the conditions and $translated to your own strings.

If you don't know the $domain, you can skip it. This version ignores it and uses a switch instead:

<?php
add_filter( 'gettext', 'translate_strings', 20, 3 );

function translate_strings( $translated, $original, $domain ) {
	switch ( $original ) {
		case 'Store':
			$translated = 'Exposition';
			break;
		case 'General Setting':
			$translated = 'Paramètres';
			break;
	}
	return $translated;
}

Without the domain check, every plugin and theme using that exact string gets the new text, so keep the strings specific.

gettext runs on every translated string on every page load. Keep the function cheap: plain comparisons, no database calls.

I keep this one in my back pocket whenever I'm debugging WordPress translations. By the way, as a good French-speaking front-end dev, am I supposed to say hook? Filter?? Filtre???

Get new posts by email

New writing in your inbox. Unsubscribe anytime.