Display a singular or pluralised string in WordPress

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 _n() function.

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:

<?php
// Display a string in either singular or plural form depending
// on the number of items. _n() is a translation function so this
// will also translate where a translation is available.
$string = _n(
'item',
'items',
$number_of_items
);

Making the pluralised string dynamic using sprintf()

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 (%s, %d, %f, etc) to our original strings.

<?php
// Combine it with sprintf() to dynamically show the exact
// number of items in the resulting string.
$string = sprintf(
_n(
'%d item in stock',
'%d items in stock',
$number_of_items
),
$number_of_items
);

To learn more about available directives, see the parameters section in the PHP documentation for sprintf().

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 _n().

<?php
// Use an ACF field value to pull the number from the database.
$number_of_items = (int) get_field('my_numerical_field', $post_id );
$string = sprintf(
_n(
'%d item in stock',
'%d items in stock',
$number_of_items
),
$number_of_items
);

About the author

Phil Kurth is a web developer living in Melbourne, Australia. Phil has a long history of WordPress development and enjoys building tools to empower others in their web design/development practice.

When not working with the web, Phil is usually spending time with his two young sons or is out hiking through the Australian bush.

Posted by in WordPress Tutorials tagged

Good dev stuff, delivered.

Product news, tips, and other cool things we make.

We never share your data. Read our Privacy Policy

© 2016 – 2024 Hookturn Digital. All rights reserved.