Using WordPress ‘gettext_with_context_{$domain}’ PHP filter

The gettext_with_context_{$domain} WordPress PHP filter allows you to modify the translation of text based on context information within a specific text domain.

Usage

add_filter('gettext_with_context_example_domain', 'your_custom_function', 10, 4);

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

    return $translation;
}

Parameters

  • $translation (string) – The translated text.
  • $text (string) – The original text to translate.
  • $context (string) – Context information for the translators.
  • $domain (string) – Text domain, a unique identifier for retrieving translated strings.

More information

See WordPress Developer Resources: gettext_with_context_{$domain}

Examples

Changing a specific translation in a theme

Change the translation of ‘Read more’ in the ‘my_theme’ text domain.

add_filter('gettext_with_context_my_theme', 'change_read_more_translation', 10, 4);

function change_read_more_translation($translation, $text, $context, $domain) {
    if ($text === 'Read more') {
        $translation = 'Continue reading';
    }
    return $translation;
}

Modifying a translation based on context

Modify the translation of ‘Post’ only in the context of ‘Admin menu’.

add_filter('gettext_with_context_example_domain', 'modify_post_translation', 10, 4);

function modify_post_translation($translation, $text, $context, $domain) {
    if ($text === 'Post' && $context === 'Admin menu') {
        $translation = 'Article';
    }
    return $translation;
}

Changing a translation for a specific plugin

Change the translation of ‘Add New’ in the ‘my_plugin’ text domain.

add_filter('gettext_with_context_my_plugin', 'change_add_new_translation', 10, 4);

function change_add_new_translation($translation, $text, $context, $domain) {
    if ($text === 'Add New') {
        $translation = 'Create New';
    }
    return $translation;
}

Adding a prefix to a translation

Add a prefix to the translation of ‘Save Changes’ in the ‘my_theme’ text domain.

add_filter('gettext_with_context_my_theme', 'add_prefix_save_changes', 10, 4);

function add_prefix_save_changes($translation, $text, $context, $domain) {
    if ($text === 'Save Changes') {
        $translation = 'Important: ' . $translation;
    }
    return $translation;
}

Uppercasing a specific translation

Uppercase the translation of ‘Submit’ in the ‘my_plugin’ text domain.

add_filter('gettext_with_context_my_plugin', 'uppercase_submit_translation', 10, 4);

function uppercase_submit_translation($translation, $text, $context, $domain) {
    if ($text === 'Submit') {
        $translation = strtoupper($translation);
    }
    return $translation;
}