Learn how to use gettext functions to make texts in themes and plugins translatable in WPML.
To ensure texts in themes and plugins are translatable (opens in a new tab), and correctly appear on your site, you need to meet two conditions:
- Wrap texts in a gettext function
- Include a text domain argument
Gettext Basics
Consider the following string, “Thank you!”, that belongs to the “my-plugin-domain” domain:
__( 'Thank you!', 'my-plugin-domain' );
To echo the string to the browser, use the _e() function:
_e( 'Thank you!', 'my-plugin-domain' );
When using HTML, wrap it within HTML tags:
<h2><?php _e( 'Thank you!', 'my-plugin-domain' ); ?></h2>
If you have a link separated from the surrounding text, use the esc_html_e() function:
<a href="http://wpml.org/" ><?php esc_html_e( 'Translated with WPML', 'my-domain' ); ?></a>
Gettext Best Practices
1. Never wrap a variable or constant in a gettext function
This will make the strings unscannable, and therefore untranslatable.
Incorrect
<?php if ( $morning ) { define( 'GREETING', 'Good morning' ); } else { define( 'GREETING', 'Good afternoon' ); } _e( GREETING, 'my-domain' ); ?>
Correct
<?php if ( $morning ) { _e( 'Good morning', 'my-domain' ); } else { _e( 'Good afternoon', 'my-domain' ); } ?>
2. Escape Output for Security
If a string is immediately rendered in the output, use escaping functions, like esc_html_ (opens in a new tab) and esc_attr_ (opens in a new tab) to protect against XSS attacks.
echo '<div>' . esc_html__( 'Back to homepage', 'my-domain' ) . '</div>';
3. Add Comments for Translators
This helps translators understand the context in which the texts or variables appear.
/* translators: %1$s is status label (e.g. "active" and %2$s is quantity of bits/s (e.g. 12 Gbit/s) */ printf( esc_html__( 'State of your network is %1$s. Maximum download speed is %2$s.', 'my-plugin-domain' ), $state, $speed );
Additional Resources
To learn more about gettext, see the official WordPress codex (opens in a new tab).