Using WordPress ‘get_translations_for_domain()’ PHP function

The get_translations_for_domain() WordPress PHP function returns the Translations instance for a specific text domain.

Usage

$translations = get_translations_for_domain($domain);

Parameters

  • $domain (string) – The text domain, which serves as a unique identifier for retrieving translated strings.

More information

See WordPress Developer Resources: get_translations_for_domain

Examples

Load Translation Instance for a Theme

Retrieve the translation instance for a theme’s text domain.

$domain = 'my_theme';
$translations = get_translations_for_domain($domain);

Load Translation Instance for a Plugin

Retrieve the translation instance for a plugin’s text domain.

$domain = 'my_plugin';
$translations = get_translations_for_domain($domain);

Translate a String with a Loaded Translation Instance

Translate a string using the translation instance for a specific text domain.

$domain = 'my_theme';
$translations = get_translations_for_domain($domain);
$translated_string = $translations->translate('Hello, world!');
echo $translated_string;

Use Translation Instance with a Formatted String

Translate a string with placeholders using the translation instance for a specific text domain.

$domain = 'my_theme';
$translations = get_translations_for_domain($domain);
$translated_string = $translations->translate('Welcome, %s!');
echo sprintf($translated_string, 'John');

Check if a Translation Instance is Empty

Check if the translation instance for a specific text domain is empty, and if it is, provide a default translation.

$domain = 'my_theme';
$translations = get_translations_for_domain($domain);

if ($translations->is_empty()) {
    $translated_string = 'Default translation';
} else {
    $translated_string = $translations->translate('Original text');
}

echo $translated_string;