• Skip to primary navigation
  • Skip to main content
Sal Ferrarello
  • About Sal Ferrarello
  • Speaking
  • Connect
    Mastodon GitHub Twitter (inactive)
You are here: Home / Dev Tips / Why __() needs a hardcoded string in WordPress

Why __() needs a hardcoded string in WordPress

Last updated on June 18, 2020 by Sal Ferrarello

When using a WordPress translation function, e.g. __(), you need to use a hardcoded string (not a variable).

Good

echo __( 'My message', 'salcode-example' );

Bad

$msg = 'My message';
echo __( $msg, 'salcode-example' );

Why?

While the two examples above behave in the same manner, the difference occurs when creating a translation file (a process called localization, which is often abbreviated l10n).

When creating a translation file, the first step is to generate a list of strings to be translated. The gettext program creates the list of strings by searching the source code and identifying translation functions and the strings that appear in them.

The gettext program uses regular expressions, it does not analyze how any of the code runs. If you use a variable instead of a hardcoded string, gettext will be unaware of the string that needs to be translated.

Strings to be translated are identified using regular expressions.

In the following, gettext would fail to identify My message as a string to be translated because it does not directly appear in the __() function call.

$msg = 'My message';
echo __( $msg, 'salcode-example' );

Text Domains

The second parameter of __(), the text domain, should be hardcoded as well. The text domain will not be identified by gettext if a variable is used. Mark Jaquith has written more about this in his post Translating WordPress Plugins and Themes: Don’t Get Clever.

Variable Content in Translated Strings

In the case where your string has variable content inside it, you can use placeholders in your strings along with printf. See the WordPress documentation on placeholders when internationalizing your code.

Sal Ferrarello
Sal Ferrarello (@salcode)
Sal is a PHP developer with a focus on the WordPress platform. He is a conference speaker with a background including Piano Player, Radio DJ, Magician/Juggler, Beach Photographer, and High School Math Teacher. Sal can be found professionally at WebDevStudios, where he works as a senior backend engineer.

Share this post:

Share on TwitterShare on FacebookShare on LinkedInShare on EmailShare on Reddit

Filed Under: Dev Tips, Programming, Recommendations Tagged With: Internationalization (I18n), WordPress

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2023 · Bootstrap4 Genesis on Genesis Framework · WordPress · Log in