2017-10-21, 09:39 AM
@"andrewjs18" asked me: "is it possible to shorten threads and posts counters to something more readable by displaying a letter for big numbers, much like Facebook and other companies do?". Yes. Thanks to MyBB's customizability, it is possible. Unfortunately there are not hooks available to easily tweak in this little but handy functionality, so we will use Patches to sneak in our code. Before diving into the tutorial, make sure you have downloaded and installed Patches.
MyBB 1.6 and 1.8 are supported, although the search patterns for every patch has been taken from MyBB 1.8.12. You may need to use different search patterns for older versions of MyBB.
This tutorial will apply to every number displayed within the MyBB environment, it is not limited to post and thread counters.
The final result:
1. Add the converter function
Within your ACP, go to Plugins > Patches, add, save and apply a new patch with the following configuration:
File: inc/functions.php
Title: my_number_shorten
Search pattern
function my_number_format($number)
Insert before
// Shortens a number and attaches K, M, B, etc. accordingly @https://stackoverflow.com/questions/4371059/shorten-long-numbers-to-k-m-b
function my_number_shorten($number, $precision = 1, $divisors = null) {
// Setup default $divisors if not provided
if (!isset($divisors)) {
$divisors = array(
pow(1000, 1) => 'k', // Thousand
pow(1000, 2) => 'm', // Million
pow(1000, 3) => 'b', // Billion
pow(1000, 4) => 't', // Trillion
);
}
// Loop through each $divisor and find the
// lowest amount that matches
foreach ($divisors as $divisor => $shorthand) {
if (abs($number) < ($divisor * 1000)) {
// We found a match!
break;
}
}
// We found our match, or there were no matches.
// Either way, use the last defined value for $divisor.
return 0 + number_format($number / $divisor, $precision) . $shorthand;
}
2. Modify my_number_format
Time to alter the actual MyBB's custom number formatting function. Add, save and apply 2 new patches with the following configurations:
File: inc/functions.php
Title: my_number_format's edit 1
Search pattern
return number_format((double)$number, $decimals, $mybb->settings['decpoint'], $mybb->settings['thousandssep']);
Insert before
if ($number > 999) {
return my_number_shorten($number);
}
File: inc/functions.php
Title: my_number_format's edit 2
Search pattern
return number_format($number, 0, $mybb->settings['decpoint'], $mybb->settings['thousandssep']);
Insert before
if ($number > 999) {
return my_number_shorten($number);
}
3. Enjoy!
All big numbers will be now converted to the corresponding shorthand version. You can edit the letter attached to thousands, millions, billions or trillions in the my_number_shorten() function. The crucial part is:
$divisors = array(
pow(1000, 1) => 'k', // Thousand
pow(1000, 2) => 'm', // Million
pow(1000, 3) => 'b', // Billion
pow(1000, 4) => 't', // Trillion
);
By default, lowercase letters are used but you can use whatever you want.