Changing Core WordPress Strings

One of the lesser known filters in WordPress is gettext. All strings that are run through the WordPress translation functions are also run through this filter after being translated thanks to a ticket I opened way back in 2008. That means you can actually use it to change pretty much any string in WordPress, namely in the admin area.

I’ve used this in some plugins I’ve written in the past and it works incredibly well.

My co-worker and one of the lead developers of WordPress Peter Westwood (westi) wrote a really good blog post about this, however I wasn’t completely happy with his code so I’m writing this blog post to share how I would write some code to take advantage of this versatile filter. Don’t get me wrong — he wrote good and valid code, but it’s not exactly the easiest thing for a novice to extend for their own uses.

function youruniqueprefix_filter_gettext( $translated, $original, $domain ) {

	// This is an array of original strings
	// and what they should be replaced with
	$strings = array(
		'View all posts filed under %s' => 'See all articles filed under %s',
		'Howdy, %1$s' => 'Greetings, %1$s!',
		// Add some more strings here
	);

	// See if the current string is in the $strings array
	// If so, replace it's translation
	if ( isset( $strings[$original] ) ) {
		// This accomplishes the same thing as __()
		// but without running it through the filter again
		$translations = &get_translations_for_domain( $domain );
		$translated = $translations->translate( $strings[$original] );
	}

	return $translated;
}

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

So as you can see at it’s core it accomplishes the same thing as Peter’s code however my code should be a bit more clear on how to make it translate multiple strings.

Hope someone finds this helpful! :)

8 thoughts on “Changing Core WordPress Strings

  1. Pingback: How to do damn near anything with WordPress – Stephanie Leary

  2. Pingback: on the Edit Media Page in WP 3.5 — ms-studio.net

  3. That’s awesome.. i was looking to a great solution not to use plugin “Codestyling Localization” and that is exactly what i need. Simple code to force custom translations. So changes won’t be lost after a plugin update.

Leave a Reply