gettext │ filter-hook │ WP 2.0.11

Allows you to change a translated string (text).

Usage

add_filter( 'gettext', 'wp_kama_gettext_filter', 10, 3 );

/**
 * Function for `gettext` filter-hook.
 * 
 * @param string $translation Translated text.
 * @param string $text        Text to translate.
 * @param string $domain      Text domain. Unique identifier for retrieving translated strings.
 *
 * @return string
 */
function wp_kama_gettext_filter( $translation, $text, $domain ){
	// filter...
	return $translation;
}
$translation(string)
Translated text. Marked as msgstr in *.po files.
$text(string)
Text to translate. Marked as msgid in *.po files.
$domain(string)
Text domain. A unique identifier used to retrieve translated strings. Specified when the translation MO file is loaded by load_textdomain().

Examples

#1 Replace "Comments" with "Reviews"

Replace the "Comments" heading with "Reviews" on the admin Comments management page.

On the Comments management page (edit-comments.php), the word "Comments" is output by this code:

_e( 'Comments' );

The _e() function and several others are based on translate(), where this hook fires.

Because a huge number of translations pass through the filter and we need to change one phrase only in the required place, the example checks that:

  • The word "Comments" is being translated.
  • The requested domain is default (the WordPress core translation).
add_filter( 'gettext', 'filter_gettext', 10, 3 );

function filter_gettext( $translation, $text, $domain ) {
	if ( $text === 'Comments' && $domain === 'default' ) {
		$translation = 'Reviews';
	}

	return $translation;
}

Why does the word "Comments" in the right-hand menu remain unchanged in the screenshots? In wp-admin/menu.php, the menu item is generated by this code:

$menu[25] = array(
	/* translators: %s: Number of comments. */
	sprintf( __( 'Comments %s' ), '<span class="awaiting-mod count-' . absint( $awaiting_mod ) . '"><span class="pending-count" aria-hidden="true">' . $awaiting_mod_i18n . '</span><span class="comments-in-moderation-text screen-reader-text">' . $awaiting_mod_text . '</span></span>' ),
	'edit_posts',
	'edit-comments.php',
	'',
	'menu-top menu-icon-comments',
	'menu-comments',
	'dashicons-admin-comments',
);

The translatable phrase here is Comments %s, so the code must be changed accordingly:

add_filter( 'gettext', 'filter_gettext', 10, 3 );

function filter_gettext( $translation, $text, $domain ) {
	if ( $text === 'Comments %s' && $domain === 'default' ) {
		$translation = 'Reviews %s';
	}

	return $translation;
}

Changelog

Since 2.0.11 Introduced.

Where the hook is called

translate()
gettext
wp-includes/l10n.php 207
$translation = apply_filters( 'gettext', $translation, $text, $domain );

Where the hook is used in WordPress

Usage not found.