Using WordPress ‘ngettext_{$domain}’ PHP filter

The ngettext_{$domain} WordPress PHP filter allows you to modify the singular or plural form of a string based on a domain and a number.

Usage

add_filter( 'ngettext_example_domain', 'custom_ngettext_example_domain', 10, 5 );

function custom_ngettext_example_domain( $translation, $single, $plural, $number, $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.
  • $domain (string): Text domain. Unique identifier for retrieving translated strings.

More information

See WordPress Developer Resources: ngettext_{$domain}

Examples

Change plural form for the “example” domain

Modify the plural form for a string in the “example” domain based on the number of items:

add_filter( 'ngettext_example', 'custom_ngettext_example', 10, 5 );

function custom_ngettext_example( $translation, $single, $plural, $number, $domain ) {
    if ( $number > 1 ) {
        $translation = $plural . " (modified)";
    }
    return $translation;
}

Change singular form for the “example” domain

Modify the singular form for a string in the “example” domain:

add_filter( 'ngettext_example', 'custom_ngettext_example', 10, 5 );

function custom_ngettext_example( $translation, $single, $plural, $number, $domain ) {
    if ( $number == 1 ) {
        $translation = $single . " (modified)";
    }
    return $translation;
}

Change plural form for a specific number

Modify the plural form for a string in the “example” domain when the number is 5:

add_filter( 'ngettext_example', 'custom_ngettext_example', 10, 5 );

function custom_ngettext_example( $translation, $single, $plural, $number, $domain ) {
    if ( $number == 5 ) {
        $translation = $plural . " (special case)";
    }
    return $translation;
}

Add a prefix to translations

Add a prefix to the translated text in the “example” domain:

add_filter( 'ngettext_example', 'custom_ngettext_example', 10, 5 );

function custom_ngettext_example( $translation, $single, $plural, $number, $domain ) {
    $translation = "Prefix: " . $translation;
    return $translation;
}

Change translation based on custom logic

Modify the translation for a string in the “example” domain based on custom logic:

add_filter( 'ngettext_example', 'custom_ngettext_example', 10, 5 );

function custom_ngettext_example( $translation, $single, $plural, $number, $domain ) {
    if ( custom_logic_function() ) {
        $translation = $single;
    } else {
        $translation = $plural;
    }
    return $translation;
}