Using WordPress ‘ngettext’ PHP filter

The ngettext WordPress PHP filter helps you translate singular and plural forms of a string based on a given number.

Usage

$result = apply_filters('ngettext', $translation, $single, $plural, $number, $domain);

// your custom code here

return $result;

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

Examples

Basic Usage

In this example, the filter translates the singular and plural forms of the word “comment”.

function translate_comments($translation, $single, $plural, $number, $domain) {
  if ('my_domain' === $domain) {
    if ($number == 1) {
      return "1 comment";
    } else {
      return "{$number} comments";
    }
  }
  return $translation;
}
add_filter('ngettext', 'translate_comments', 10, 5);

Translate “Like” and “Likes”

In this example, we translate the words “like” and “likes” based on the number of likes.

function translate_likes($translation, $single, $plural, $number, $domain) {
  if ('my_domain' === $domain) {
    return ($number == 1) ? "{$number} like" : "{$number} likes";
  }
  return $translation;
}
add_filter('ngettext', 'translate_likes', 10, 5);

Translate “Post” and “Posts”

In this example, we translate the words “post” and “posts” based on the number of posts.

function translate_posts($translation, $single, $plural, $number, $domain) {
  if ('my_domain' === $domain) {
    return ($number == 1) ? "{$number} post" : "{$number} posts";
  }
  return $translation;
}
add_filter('ngettext', 'translate_posts', 10, 5);

Translate “Category” and “Categories”

In this example, we translate the words “category” and “categories” based on the number of categories.

function translate_categories($translation, $single, $plural, $number, $domain) {
  if ('my_domain' === $domain) {
    return ($number == 1) ? "{$number} category" : "{$number} categories";
  }
  return $translation;
}
add_filter('ngettext', 'translate_categories', 10, 5);

Translate “Tag” and “Tags”

In this example, we translate the words “tag” and “tags” based on the number of tags.

function translate_tags($translation, $single, $plural, $number, $domain) {
  if ('my_domain' === $domain) {
    return ($number == 1) ? "{$number} tag" : "{$number} tags";
  }
  return $translation;
}
add_filter('ngettext', 'translate_tags', 10, 5);