The ngettext_with_context WordPress PHP filter allows you to filter the singular or plural form of a string with gettext context depending on the number provided.
Usage
apply_filters('ngettext_with_context', $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
Examples
Basic usage
Filter the translation of the singular or plural form of the string based on the number of comments.
add_filter('ngettext_with_context', 'my_custom_plural_comments', 10, 6); function my_custom_plural_comments($translation, $single, $plural, $number, $context, $domain) { if ($context == 'comments' && $domain == 'my_theme_domain') { $translation = $number == 1 ? $single : $plural; } return $translation; }
Custom plural form
Customize the plural form of a string based on a specific context and domain.
add_filter('ngettext_with_context', 'my_custom_plural_form', 10, 6); function my_custom_plural_form($translation, $single, $plural, $number, $context, $domain) { if ($context == 'custom_form' && $domain == 'my_plugin_domain') { $translation = $number == 1 ? $single : str_replace('%s', $number, $plural); } return $translation; }
Custom text domain
Use a custom text domain for translating strings with a specific context.
add_filter('ngettext_with_context', 'my_custom_text_domain', 10, 6); function my_custom_text_domain($translation, $single, $plural, $number, $context, $domain) { if ($context == 'my_context' && $domain == 'my_theme_domain') { $translation = $number == 1 ? $single : $plural; } return $translation; }
Change plural form based on a condition
Modify the plural form of a string based on a specific condition.
add_filter('ngettext_with_context', 'my_custom_plural_condition', 10, 6); function my_custom_plural_condition($translation, $single, $plural, $number, $context, $domain) { if ($context == 'products' && $domain == 'my_plugin_domain') { if (apply_filters('my_custom_condition', false)) { $translation = $number == 1 ? $single : str_replace('%s', $number, $plural); } } return $translation; }