Use translated taxonomy labels in plugin

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?

Read More

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?

Related posts

2 comments

  1. 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:

    // bare number, needed for _n()
    $num  = count( $created );
    
    // Singular or plural, we use %s, because we don't know what 
    // number_format_i18n() will return.
    $text = _n(
        'Created %s category',
        'Created %s categories',
        $num,
        'unique_plugin_textdomain'
    );
    // thousands separator etc.
    $display_number = number_format_i18n( $num );
    // Finally, the result:
    $message        = sprintf( $text, $display_number );
    
  2. Yes, register_taxonomy() expects array of translated labels and get_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...).

Comments are closed.