How to escape single and plural i18n text strings?

I’ve come across the esc_html_e() and esc_attr_e() functions which allow me to escape translated text strings. I’m now using these instead of _e() where appropriate.

The _n() function allows for both single and plural forms to be translated. I don’t think there’s an esc_attr_n() function in WordPress. How can I escape the translated text in this case? Here’s my current use of the _n() function:

printf(
    _n(
        '1 item',
        '%d items',
        $count,
        'textdomain'
    ),
    number_format_i18n( $count )
);

Ref https://codex.wordpress.org/Function_Reference/_n

1 Answer
1

esc_html_e() and esc_attr_e() are merely wrapper functions for _ to save a little bit of typing and help with readability. You’re right, there isn’t one for _n, so you’ll just need to do the “wrapping” yourself:

printf(
    esc_attr(
        _n(
            '%s item',
            '%s items',
            $count,
            'textdomain'
        )
    ),
    number_format_i18n( $count )
);

Leave a Comment