Select Page

Use WordPress String Translation gettext Hook to Customize Plugins

by | Sep 30, 2019 | WordPress Maintenance, WordPress Plugin Development

Scenario: Why I Needed to Learn WordPress String Translation

Say you’ve found a plugin you want to use. It meets all the requirements, but it has one or two minor pieces of text you don’t care for. One solution is to swap that text using jQuery on document load, but then you have the unprofessional flash of old text before it turns into the new.

But here’s some great news: there’s a better solution, and it’s found in the WordPress string translation hooks! The folks at WordPress provide these functions to make translating to other languages easy, but we can also use these to intercept strings and change them before they are written to the page!

In my case I needed to change the label of a front-end field used by The Events Calendar plugin, and below is how I did it.

A Bit Of Digging: Sifting Through WordPress Plugin Code to Find the Hook

The first step is the trickiest, and that’s finding the spot in the plugin’s code that declares the string and the text domain it’s attached to. You can cheat a bit and get the text domain from the root plugin file, then do a bit of trial and error in the string.

In my case, I found my prize at wp-content/plugins/the-events-calendar/src/views/modules/meta/details.php – I find that the most effective approach is to follow the train of breadcrumbs in the form of PHP include statements. The below screenshot shows what I found:

Plugin source code that revealed the text and domain needed to apply WordPress string translation

The Code

// String Changes
function text_string_changes( $translated_text, $text, $domain ) {

	switch ( $translated_text ) {
		case 'Website:' :
			$translated_text = __( 'Registration URL:', 'the-events-calendar' );
			break;
		}
	
	return $translated_text;
}
add_filter( 'gettext', 'text_string_changes', 20, 3 );

The WordPress string translation successfully took hold and changed "Website" to "Registration URL"

Closing Thoughts

Hopefully this helps you deliver a clean solution to your client, and should you want related readings, check out my previous article about WordPress plugin development, and my last post about triggering functions when a new WordPress post is created.