为WordPress主题添加文章字数和阅读时间

  • 酉灿
  • WordPress
  • Jul 23, 2021

显示文章字数和阅读时间,这功能有什么用呢,我也不知道,不过有用户说人家有我们能不能也加一个,那就加呗,就有这篇为WordPress主题添加文章字数和阅读时间。
具体代码这里也分享一下:

 

文章字数统计


 
  1. // 字数统计
  2. function zm_count_words ($text) {
  3. global $post;
  4. if ( '' == $text ) {
  5. $text = $post->post_content;
  6. if (mb_strlen($output, 'UTF-8') < mb_strlen($text, 'UTF-8')) $output .= '<span class="word-count">共' . mb_strlen(preg_replace('/\s/','',html_entity_decode(strip_tags($post->post_content))),'UTF-8') .'字</span>';
  7. return $output;
  8. }
  9. }

代码添加到当前主题函数模板 functions.php 中。

文章阅读时间


 
  1. // 阅读时间
  2. function zm_get_reading_time($content) {
  3. $zm_format = '<span class="reading-time">阅读时间%min%分%sec%秒</span>';
  4. $zm_chars_per_minute = 300; // 估算1分种阅读字数
  5.  
  6. $zm_format = str_replace('%num%', $zm_chars_per_minute, $zm_format);
  7. $words = mb_strlen(preg_replace('/\s/','',html_entity_decode(strip_tags($content))),'UTF-8');
  8.  
  9. $minutes = floor($words / $zm_chars_per_minute);
  10. $seconds = floor($words % $zm_chars_per_minute / ($zm_chars_per_minute / 60));
  11. return str_replace('%sec%', $seconds, str_replace('%min%', $minutes, $zm_format));
  12. }
  13.  
  14. function zm_reading_time() {
  15. echo zm_get_reading_time(get_the_content());
  16. }

代码添加到当前主题函数模板 functions.php 中。

调用文章字数和阅读时间代码

显示文章字数代码:


 
  1. <?php echo zm_count_words($text); ?>

显示阅读时间代码:


 
  1. <?php zm_reading_time(); ?>

将上述调用代码加到当前主题正文模板的适当位置即可。

不过字数统计和阅读时间不是很精确,特别是阅读时间,更是扯淡,默认是按CCTV广播员语速定的。


写完这篇文章,发现网上有更简洁的代码,区别是上面的代码精确到秒,下面的代码只估算到分。


 
  1. function count_words_read_time () {
  2. global $post;
  3. $text_num = mb_strlen(preg_replace('/\s/','',html_entity_decode(strip_tags($post->post_content))),'UTF-8');
  4. $read_time = ceil($text_num/300); // 修改数字300调整时间
  5. $output .= '本文共计' . $text_num . '个字,预计阅读时长' . $read_time . '分钟。';
  6. return $output;
  7. }

调用代码:


 
  1. <?php echo count_words_read_time(); ?>

打赏