折腾的路上永不止,很奇怪对于一篇文章内的字数和阅读时间有啥用呢,这我也不知道,也不敢问。不过有朋友说人家的主题里都有,博主你知道怎么加一个吗?说实话我是不知道的,不过在鸟哥这里看到了这个教程,所以今天想着必须安排上。
具体教程非常交单,没有想象中的那么复杂,只要添加些简单的代码便能轻松搞定。
文章字数统计
// 字数统计 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 .= '<span class="word-count">共' . mb_strlen(preg_replace('/\s/','',html_entity_decode(strip_tags($post->post_content))),'UTF-8') .'字</span>'; return $output; } }
将上述代码添加到WordPress主题里的函数模板functions.php中便可。
文章阅读时间
// 阅读时间 function zm_get_reading_time($content) { $zm_format = '<span class="reading-time">阅读时间%min%分%sec%秒</span>'; $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()); }
将上述代码添加到WP主题里的函数模板functions.php之中。
调用文章字数和阅读时间代码
显示文章字数代码:
<?php echo zm_count_words($text); ?>
显示阅读时间代码:
<?php zm_reading_time(); ?>
将上述调用代码加到当前主题正文模板的适当位置即可,不过要注意的是,统计的字数和阅读时间并不是百分百精准。
特别是阅读时间,更是扯淡,默认是按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; }
当然,对于这个功能Ourboke联盟认为意义并不是太大,不过考虑到每个人的喜好都不一样,有喜欢的朋友们可以收藏起来,方便日后使用。