字数自动统计和预估阅读时间这2个小功能其实是非常人性化的,指点聚在开发过程中恰好需要用到这样的功能,于是打开网络笔记,找出了曾经的记录,代码作者歪主题也不得而知,感谢作者~
下面正文开始
首先为 WordPress 添加文章字数统计
先将以下代码放在函数文件中或者方式不限只要调用到代码就行
// 指点聚 // https://www.zhidianju.com function count_words ($text) { global $post; if ( '' == $text ) { $text = $post->post_content; if (mb_strlen($output, 'UTF-8') < mb_strlen($text, 'UTF-8')) $output .= '本文共' . mb_strlen(preg_replace('/s/','',html_entity_decode(strip_tags($post->post_content))),'UTF-8') . '个字'; return $output; } }
然后在你需要显示的位置调用以下代码
count_words ($text);
为 WordPress 添加预计阅读时间
同样将下面代码放入函数文件中
function waizhuti_read_time($content){ $text = trim(strip_tags( get_the_content())); $text_num = mb_strlen($text, 'UTF-8'); $read_time = ceil($text_num/400); $content = '<div class="read-time">预计阅读时间 <span>' . $read_time . '</span> 分钟</div>' . $content; return $content; } add_filter ( 'the_content', 'waizhuti_read_time');
以上代码中第 4 行的数值 400,是根据百度出来的“一般人的阅读速度平均为(300~500)字/分钟”取中间值,如果你觉得 400 太慢可以自行修改,需要自定义样式的可以对 .read-time 在 css 里自定义样式。
以上两小功能合并
如果你两个小功能都需要,那么给出一个合并的代码吧,
将以下代码放入函数文件中
// 字数和预计阅读时间统计 // https://www.zhidianju.com function count_words_read_time () { global $post; $text_num = mb_strlen(preg_replace('/s/','',html_entity_decode(strip_tags($post->post_content))),'UTF-8'); $read_time = ceil($text_num/400); $output .= '本文共' . $text_num . '个字,预计要阅读' . $read_time . '分钟。'; return $output; }
其中,以上的 400 为阅读速度,可以更改。如只需要输出阅读时间或文章字数,只需要修改删除第 6 行某些代码即可,具体请自行 DIY 吧。
接着还是调用函数到你需要显示的位置
count_words_read_time();
拓展阅读(ceil() 函数)
ceil() 函数向上舍入为最接近的整数。意思就是说返回不小于 x 的下一个整数,x 如果有小数部分则进一位。ceil() 返回的类型仍然是 float,因为 float 值的范围通常比 integer 要大。
例子
- ceil(0.60),输出 1;
- ceil(0.4) ,输出 1;
- ceil(5),输出 5;
- ceil(5.1),输出 6;
- ceil (-5.1),输出 -5;
- ceil(-5.9),输出 -5;
教程结束,希望对你有用处!
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.