Skip to content

Instantly share code, notes, and snippets.

@joshfeck
Created August 3, 2018 16:44
Show Gist options
  • Save joshfeck/62183600028f7ff7bd135bfdc89c5684 to your computer and use it in GitHub Desktop.
Save joshfeck/62183600028f7ff7bd135bfdc89c5684 to your computer and use it in GitHub Desktop.
Translate strings with context. Important: use this filter function only for i18n-ready strings that are wrapped in esc_html_x() or similar.
<?php
//* Please do NOT include the opening php tag, except of course if you're starting with a blank file
add_filter(
'gettext_with_context',
'mycustom_filter_gettext_with_context',
10,
4
);
function mycustom_filter_gettext_with_context(
$translated,
$original,
$context,
$domain
) {
// This is an array of original strings
// and what they should be replaced with
$strings = array(
'Attendee %d' => 'Participant %d',
// more strings with context here if needed
);
// See if the current string is in the $strings array
// If so, replace its translation
if ( isset( $strings[$original] ) ) {
// This accomplishes the same thing as __()
// but without running it through the filter again
$translations = get_translations_for_domain( $domain );
$translated = $translations->translate( $strings[$original] );
}
return $translated;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment