我试图在正在构建的网站上显示帖子视图,以使其显示为1.1k而不是1000。这是一个Wordpress网站,尝试将自定义功能添加到该网站时遇到了麻烦。每次添加一些我在这里找到的代码片段时,它都会使网站完全崩溃。
这是当前的代码-它只是计算落在帖子上的用户以及管理员能够手动设置帖子数的次数。
if(!function_exists('davenport_getPostViews')):
function davenport_getPostViews($postID){
$count_key = '_davenport_post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count == ''){
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
return 0;
}
return $count;
}
endif;
if(!function_exists('davenport_setPostViews')):
function davenport_setPostViews() {
global $post;
$postID = $post->ID;
$count_key = '_davenport_post_views_count';
$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++;
update_post_meta($postID, $count_key, $count);
}
}
add_action('davenport_set_post_views', 'davenport_setPostViews');
endif;
在我尽力解决这一问题时,任何帮助将不胜感激。
答案 0 :(得分:0)
一种简单的方法是将其分开。所以这样做看起来像这样:
<?php
function DisplayViews($views){
if($views > 0){
$display = round($views / 1000, 2);
return $display."k";
} else {
return "0";
}
}
echo DisplayViews($count); //$count should be your view count
?>
尽管上面的方法可以很好地工作,但我建议您进行更多检查,以便只有10个视图时不会显示0.01k。观看次数超过999,999时也是如此。
要做这些检查,您需要做的是:
if($views <= 999){
//Display number without letter "K"
}
if($views > 999999){
//Display number with the letter "m"
}
因此将这两个数字结合起来可以检查数字是否小于100,也可以检查数字是否大于999,999,这意味着您不会在最后显示带有错误字母的数字。最终代码将如下所示:
<?php
function DisplayViews($views){
if($views > 0){
if($views <= 999){
return $views;
} elseif($views > 999999){
$display = round($views / 1000000, 2);
return $display."M";
} else {
$display = round($views / 1000, 2);
return $display."K";
}
} else {
return "0";
}
}
echo DisplayViews($count);
?>
答案 1 :(得分:0)
在您的计数变量上调用此函数。
function humanize_number($input){
$input = number_format($input);
$input_count = substr_count($input, ',');
if($input_count != '0'){
if($input_count == '1'){
return substr($input, 0, -4).'k';
} else if($input_count == '2'){
return substr($input, 0, -8).'mil';
} else if($input_count == '3'){
return substr($input, 0, -12).'bil';
} else {
return;
}
} else {
return $input;
}
}
答案 2 :(得分:0)
类似于将字节大小转换为人类可读格式。
function getReadableCount($count, $dec = 2) { $units = ['K', 'M', 'B']; for ($i = count($units); $i > 0; $i --) { $base = pow(1000, $i); if ($count >= $base) { return round($count/$base, $dec) . $units[$i-1]; } } return $count; } echo getReadableCount($count, 1);
答案 3 :(得分:0)
如果您在此处查看GitHub帖子:https://gist.github.com/bcole808/9371754,他们会说您可以使用
function numberAbbreviation($number) {
$abbrevs = array(12 => "T", 9 => "B", 6 => "M", 3 => "K", 0 => "");
foreach($abbrevs as $exponent => $abbrev) {
if($number >= pow(10, $exponent)) {
$display_num = $number / pow(10, $exponent);
$decimals = ($exponent >= 3 && round($display_num) < 100) ? 1 : 0;
return number_format($display_num,$decimals) . $abbrev;
}
}
}