### [为WordPress主题添加文章字数和阅读时间](https://www.prosaas.cn/article/9711) **Published:** 2019-10-21T03:32:51 **Author:** 5201314 **Excerpt:** 显示文章字数和阅读时间,这功能有什么用呢,我也不知道,不过有用户说人家有我们能不能也加一个,那就加吧。下面由W… 显示文章字数和阅读时间,这功能有什么用呢,我也不知道,不过有用户说人家有我们能不能也加一个,那就加吧。下面由**WordPress教程**栏目给大家介绍为WordPress主题添加文章字数和阅读时间的方法。 ![](//zhiqipro.oss-cn-beijing.aliyuncs.com/2023/12/20231212132652574.jpg) 为WordPress主题添加文章字数和阅读时间为WordPress主题添加文章字数和阅读时间 具体代码这里也分享一下: 文章字数统计 // 字数统计 function zm\_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; } } 代码添加到当前主题函数模板 functions.php 中。 文章阅读时间 // 阅读时间 function zm\_get\_reading\_time($content) { $zm\_format = '阅读时间%min%分%sec%秒'; $zm\_chars\_per\_minute = 300; // 估算1分种阅读字数 $zm\_format = str\_replace('%num%', $zm\_chars\_per\_minute, $zm\_format); $words = mb\_strlen(preg\_replace('/\\s/','',html\_entity\_decode(strip\_tags($content))),'UTF-8'); $minutes = floor($words / $zm\_chars\_per\_minute); $seconds = floor($words % $zm\_chars\_per\_minute / ($zm\_chars\_per\_minute / 60)); return str\_replace('%sec%', $seconds, str\_replace('%min%', $minutes, $zm\_format)); } function zm\_reading\_time() { echo zm\_get\_reading\_time(get\_the\_content()); } 代码添加到当前主题函数模板 functions.php 中。 调用文章字数和阅读时间代码 显示文章字数代码: 显示阅读时间代码: 将上述调用代码加到当前主题正文模板的适当位置即可。 不过字数统计和阅读时间不是很精确,特别是阅读时间,更是扯淡,默认是按CCTV广播员语速定的。 写完这篇文章,发现网上有更简洁的代码,区别是上面的代码精确到秒,下面的代码只估算到分。 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/300); // 修改数字300调整时间 $output .= '本文共计' . $text\_num . '个字,预计阅读时长' . $read\_time . '分钟。'; return $output; } 调用代码: 以上就是为WordPress主题添加文章字数和阅读时间的详细内容,更多请关注知企PROSAAS其它相关文章! **Tags:** php, WordPress, 函数模板 **Categories:** WordPress ---