In WordPress, the recommended way to handle hard-coded strings that need to be translated is to use the __()
function, which is a shorthand for the translate()
function. Like so:
<?php
$text = __("Details matter, it’s worth waiting to get it right.", 'my-theme');
echo $text;
?>
We use the __()
function to translate the hard-coded string “Details matter, it’s worth waiting to get it right.”. The second argument to the function is a text domain, which is used to identify the theme or plugin that the string belongs to. This helps WordPress to correctly load the translation files for the string.
To actually translate the string, you need to create a translation file for your theme or plugin. This file should be named with the format {textdomain}-{locale}.mo
, where {textdomain}
is the same value as the text domain passed to the __()
function, and {locale}
is the two-letter language code for the translation. For example, if your text-domain is “my-theme” and you want to translate the string into French, the filename would be my-theme-fr.mo
.
You can use a tool like Poedit to create and edit translation files. Once you have created the translation file, you can upload it to your theme or plugin directory in a subdirectory called languages
, and WordPress will automatically load the translation when the appropriate language is selected.