Sometimes, you may need to display a string differently depending on whether a variable is singular or plural. i.e; “1 product in stock” compared to “2 products in stock”.
We could of course use an
if() statement or even a
switch() if there were multiple possibilities here, but for simple use cases, WordPress provides us with a handy function that not only handles which string to use based on a number provided but will also translate the string if it has an appropriate translation available — the
A simple example using WordPress’ _n() function
Let’s say we have a number and we just want one of two hard-coded strings based on whether that number represents a singular or pluralised value. This is how you do it:
Making the pluralised string dynamic using
It’s not uncommon to want to use the number in the rendered string. To do so, we can use PHP’s
sprintf() function and add an appropriate directive (
%f, etc) to our original strings.
To learn more about available directives, see the parameters section in the PHP documentation for
Taking it further and using by adding an ACF field value in the mix
Of course, it’s possible to pull this variable from anywhere so if you are using the Advanced Custom Fields plugin for dynamic data, you can easily pull that data from the database and use it alongside