In this tutorial, we’re going to take a look at a handy PHP function that allows you to shorten large numbers into an easy-to-read format. For instance, it will let us turn 1234
into 1.2K
or 5678900
into 5.7M
.
This can be very useful when you’re dealing with large numbers like views, followers, or anything that reaches into the thousands or beyond, and you want to keep your interface clean and simple.
In this tutorial, we will use ACPT to create field groups and assign them to our testimonial custom post type. However, this method could work with other plugins or you could use static values.
CPT Field Group Information
- Our Field Group name : posts-groups
- Metabox name : posts-metabox
- Field name : asset total
- Field Slug : asset-total
- Field Type : Number
After setting up the custom fields and field groups, populate your fields in the post.
The PHP Code Snippet
Add the following PHP function to your Child Theme’s functions.php
, or use a plugin like Code Snippets to insert the code:
<?php
function getShortNumber($number=0) {
$symbol = array('', 'K', 'M', 'B');
$exp = 0;
$dec = $number < 1001 ? 0 : 1;
$exp_max = count($symbol)-1;
$converted_value = 0;
if( $number > 0 ) {
$exp = floor( log($number)/log(1000) );
if( $exp > $exp_max ) $exp = $exp_max;
$converted_value = ( $number/pow(1000,$exp) );
}
return number_format($converted_value,$dec,'.',',').' '.$symbol[$exp];
}
Displaying on the frontend (Static Numbers)
To display this on the Frontend, navigate to the location where you want the number to appear. This can be within either a basic text element or a rich text element, depending on your design choice. In that specific area, you should echo this function:
{echo:getShortNumber(23454)}
This snippet will dynamically get the getShortNumber
function, converting the number 23454
into a more concise format, such as 23.5K
, making it easier for users to read and understand.
Make sure you whitelist the getShortNumber()
function.
Displaying on the frontend (Dynamic Numbers)
To display this dynamically on your webpage, we will use this code structure:
{echo:getShortNumber(field-name)}
This snippet is designed to call the getShortNumber
function, where field-name
should be replaced with the actual name of the field containing the number you wish to format. By doing this, the function will process the value retrieved from the specified field and convert it into a more user-friendly format.
where the “testimonials” is our custom post type, and The term “posts-metabox” refers to the name of the Metabox that we’ve created to organize and manage our fields. and “asset-total” is the slug of the specific field that contains the numeric data we want to display.
Summary
The getShortNumber
function simplifies large numbers into a readable format with suffixes, making data presentation clearer and more user-friendly.