The ngettext_with_context_{$domain} WordPress PHP filter allows you to filter the singular or plural form of a string with gettext context for a specific domain.
Usage
add_filter( 'ngettext_with_context_' . $domain, 'my_custom_function', 10, 6 );
function my_custom_function( $translation, $single, $plural, $number, $context, $domain ) {
// Your custom code here
return $translation;
}
Parameters
$translation(string) – Translated text.$single(string) – The text to be used if the number is singular.$plural(string) – The text to be used if the number is plural.$number(int) – The number to compare against to use either the singular or plural form.$context(string) – Context information for the translators.$domain(string) – Text domain. Unique identifier for retrieving translated strings.
More information
See WordPress Developer Resources: ngettext_with_context_{$domain}
Examples
Simple Translation
This example filters the singular and plural form for a specific text domain, “my-text-domain”.
add_filter( 'ngettext_with_context_my-text-domain', 'my_custom_translation', 10, 6 );
function my_custom_translation( $translation, $single, $plural, $number, $context, $domain ) {
if ( 'fruit' === $context ) {
if ( 1 === $number ) {
$translation = 'apple';
} else {
$translation = 'apples';
}
}
return $translation;
}
Custom Number Logic
This example filters the translation based on custom number logic, where the plural form is used for any number greater than 3.
add_filter( 'ngettext_with_context_example-domain', 'custom_number_logic', 10, 6 );
function custom_number_logic( $translation, $single, $plural, $number, $context, $domain ) {
if ( 'quantity' === $context ) {
if ( $number <= 3 ) {
$translation = $single;
} else {
$translation = $plural;
}
}
return $translation;
}
Dynamic Context
This example filters the translation based on a dynamic context that is passed to the function.
add_filter( 'ngettext_with_context_example-domain', 'dynamic_context', 10, 6 );
function dynamic_context( $translation, $single, $plural, $number, $context, $domain ) {
if ( 'custom_context' === $context ) {
$translation = $number === 1 ? 'custom_single' : 'custom_plural';
}
return $translation;
}
Custom Domain
This example filters the translation for a custom domain, “my-custom-domain”.
add_filter( 'ngettext_with_context_my-custom-domain', 'custom_domain_filter', 10, 6 );
function custom_domain_filter( $translation, $single, $plural, $number, $context, $domain ) {
// Your custom code here
return $translation;
}