The gettext_with_context WordPress PHP filter allows you to filter text with its translation based on context information.
Usage
add_filter('gettext_with_context', 'my_custom_function', 10, 4);
function my_custom_function($translation, $text, $context, $domain) {
// your custom code here
return $translation;
}
Parameters
$translationstring: Translated text.$textstring: Text to translate.$contextstring: Context information for the translators.$domainstring: Text domain. Unique identifier for retrieving translated strings.
More information
See WordPress Developer Resources: gettext_with_context
Examples
Replace a specific string in a plugin
Replace the “Add to Cart” text with “Buy Now” in your plugin.
add_filter('gettext_with_context', 'replace_add_to_cart', 10, 4);
function replace_add_to_cart($translation, $text, $context, $domain) {
if ('Add to Cart' === $text && 'my_plugin' === $domain) {
return 'Buy Now';
}
return $translation;
}
Change date format
Modify the date format for a specific context.
add_filter('gettext_with_context', 'change_date_format', 10, 4);
function change_date_format($translation, $text, $context, $domain) {
if ('Date Format' === $context && 'my_plugin' === $domain) {
return 'd/m/Y';
}
return $translation;
}
Translate custom taxonomy labels
Translate custom taxonomy labels for a specific text domain.
add_filter('gettext_with_context', 'translate_taxonomy_labels', 10, 4);
function translate_taxonomy_labels($translation, $text, $context, $domain) {
if ('Taxonomy Singular Name' === $context && 'my_plugin' === $domain) {
return 'My Custom Category';
}
return $translation;
}
Change default text based on user role
Modify the default text depending on the user’s role.
add_filter('gettext_with_context', 'change_text_for_user_role', 10, 4);
function change_text_for_user_role($translation, $text, $context, $domain) {
$user = wp_get_current_user();
if ('Welcome Message' === $context && 'my_theme' === $domain && in_array('subscriber', $user->roles)) {
return 'Welcome, valued subscriber!';
}
return $translation;
}
Capitalize specific text
Capitalize a specific string in a given context.
add_filter('gettext_with_context', 'capitalize_specific_text', 10, 4);
function capitalize_specific_text($translation, $text, $context, $domain) {
if ('my_text' === $text && 'my_theme' === $domain) {
return strtoupper($translation);
}
return $translation;
}