I’m writing a plugin that works with taxonomy terms. It has, among other things, the capability to create new terms. I’m going to suppose that if users have custom taxonomies, they have taken care of having the singular and plural names set up and translated.
The question is: How do I format my plugin messages to use translated labels for taxonomies?
I need to output messages such as:
- “Created 1 category.”
- “Matched 2 tags.”
- “Updated 5 movies.” (Supposing “movies” is a custom taxonomy.)
In my understanding, the (translated) singular and plural labels for a taxonomy are available as $term_object->labels->singular_name
and $term_object->labels->name
.
Is it correct to assume that these properties contain translated strings? Or is it necessary to wrap them with some i18n function?
The _n()
and the _nx()
functions provide for singular and plural forms, but it doesn’t make sense using them. I’ve been using:
$message = sprintf(
'Created %d %s',
count($created),
count($created) == 1 ?
$term_object->labels->singular_name
: $term_object->labels->name
);
What is the best practice here?
You have to use a plural aware function like
_n()
or_nx()
, because the words around the number might change in some languages depending on the amount items.For visible numbers use
number_format_i18n()
and%s
, not%d
.You cannot reuse the labels, because plural forms change depending on context in some languages.
This is how I would write your example:
Yes,
register_taxonomy()
expects array of translated labels andget_taxonomy_labels()
provides translated default fallbacks.You do not need to additionally pass labels through translation function since they assumed to be passed through it already.
Note that you do need to translate your own custom string (
Created...
).