has_translation() │ WP 6.7.0

Checks whether a translation of the specified string exists for a text domain and locale.

Searches for the string only in translation files that have already been loaded.

Does not load translations automatically. If the files for the specified text domain and locale have not yet been loaded, the result is false.

Use __() when you need to get a string translation. If the translation is missing, the function returns the original string.

No Hooks.

Returns

bool.

  • true - the string translation exists.
  • false - the translation was not found or the matching translation files are not loaded.

Usage

has_translation( $singular, $textdomain, ?string $locale ): bool;
$singular(string) (required)
The original string whose translation should be checked.
$textdomain(string)
The translation text domain.
Default: 'default'
$locale(string|null)
The translation locale, for example ru_RU. When null, the current locale is used.
Default: null

Examples

#1 Use fallback text when a translation is missing

$text = has_translation( 'Download guide', 'my-plugin' )
	? __( 'Download guide', 'my-plugin' )
	: __( 'Download', 'my-plugin' );

echo esc_html( $text );

#2 Check a translation for a specific locale

if ( has_translation( 'Download guide', 'my-plugin', 'ru_RU' ) ) {
	echo 'The Russian translation is loaded.';
}

Changelog

Since 6.7.0 Introduced.

has_translation() code WP 7.1.2

function has_translation( string $singular, string $textdomain = 'default', ?string $locale = null ): bool {
	return WP_Translation_Controller::get_instance()->has_translation( $singular, $textdomain, $locale );
}