Using WordPress ‘gettext_{$domain}’ PHP filter

The gettext_{$domain} WordPress PHP filter allows you to filter text with its translation for a specific domain.

Usage

add_filter( 'gettext_example', 'custom_text_translation', 10, 3 );

function custom_text_translation( $translation, $text, $domain ) {
  // Your custom code here

  return $translation;
}

Parameters

  • $translation (string): Translated text.
  • $text (string): Text to translate.
  • $domain (string): Text domain. Unique identifier for retrieving translated strings.

More information

See WordPress Developer Resources: gettext_{$domain}

Examples

Change ‘Read More’ Text

Change the ‘Read More’ text to ‘Continue Reading’ for the ‘twentytwentyone’ theme.

add_filter( 'gettext_twentytwentyone', 'change_read_more_text', 10, 3 );

function change_read_more_text( $translation, $text, $domain ) {
  if ( 'Read More' === $text ) {
    return 'Continue Reading';
  }
  return $translation;
}

Change the default WordPress admin footer text.

add_filter( 'gettext_default', 'change_admin_footer_text', 10, 3 );

function change_admin_footer_text( $translation, $text, $domain ) {
  if ( 'Thank you for creating with <a href="%s">WordPress</a>.' === $text ) {
    return 'Powered by <a href="%s">WordPress</a> and customized by Your Name.';
  }
  return $translation;
}

Translate Custom Plugin Strings

Translate custom strings in a plugin with the text domain ‘my-plugin’.

add_filter( 'gettext_my-plugin', 'translate_my_plugin_strings', 10, 3 );

function translate_my_plugin_strings( $translation, $text, $domain ) {
  $translations = array(
    'Hello, World!' => 'Bonjour, le monde!',
    'Goodbye!' => 'Au revoir!'
  );

  if ( isset( $translations[ $text ] ) ) {
    return $translations[ $text ];
  }

  return $translation;
}

Change ‘Add New’ Button Text

Change the ‘Add New’ button text to ‘Create New’ in the custom post type ‘book’.

add_filter( 'gettext_default', 'change_add_new_button_text', 10, 3 );

function change_add_new_button_text( $translation, $text, $domain ) {
  if ( 'book' === get_post_type() && 'Add New' === $text ) {
    return 'Create New';
  }
  return $translation;
}

Customize WooCommerce Strings

Customize WooCommerce strings with the text domain ‘woocommerce’.

add_filter( 'gettext_woocommerce', 'customize_woocommerce_strings', 10, 3 );

function customize_woocommerce_strings( $translation, $text, $domain ) {
  $translations = array(
    'Cart' => 'Basket',
    'Checkout' => 'Pay Now'
  );

  if ( isset( $translations[ $text ] ) ) {
    return $translations[ $text ];
  }

  return $translation;
}