I have the following function:
function getPostViews($postID){
$count_key = \'post_views_count\';
$count = get_post_meta($postID, $count_key, true);
You can use number_format.
$number=number_format($number);
Have a look at number_format.
For example:
$number = 1234.56;
// english notation (default)
$english_format_number = number_format($number);
// 1,235
// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56
$number = 1234.5678;
// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57
Use number_format():
number_format($number);
Your number format use was correct to get the nice formatting you are looking for. The issue I think you are running into regarding changing the format in your DB is that you are formatting the number and resaving it over itself.
For example:
$count = 5000;
$count = number_format($count);
//$count is no longer equal to 5000, it is now a string 5,000
Try using a temporary variable, that way your original $count variable won't change, and when you write back to the database, it will still be in the formatting you want.
For example:
$count = 5000;
$tmpCount = 0;
$tmpCount = number_format($count);
// $count is still 5000, and $tmpCount now holds the value 5,000.
An updated version of your code, I'm assuming you only want the meta holding the comma separated value?
function setPostViews($postID) {
//Set initial variables
$count_key = 'post_views_count';
$tmpCount = 0;
$count = get_post_meta($postID, $count_key, true);
if($count == '') {
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
} else {
$count++;
//Set tmpCount variable to hold comma separated value
$tmpCount = number_format($count);
//Comma separated value is passed into your function
update_post_meta($postID, $count_key, $tmpCount);
}
}
Was that what you were hoping for? or if you're want to only format this number this way when displaying to the user, but the db to remain proper (not comma separated), after querying the db, save both the db value and create a comma separated variable exactly as I've done above. Then on any db functions, refer to the $count variable, and on any user output functions, use the $tmpCount variable.
Again, I hope that answers your question, if it's not, please clarify.