为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 .= '<span class="word-count">共' . mb_strlen(preg_replace('/\s/','',html_entity_decode(strip_tags($post->post_content))),'UTF-8') .'字</span>'; return $output; } }
代码增加到以后主题函数模板 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()); }
代码增加到以后主题函数模板 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; }
挪用代码:
<?php echo count_words_read_time(); ?>
以上就是为WordPress主题增加文章字数以及浏览工夫的具体内容,更多请存眷资源魔其它相干文章!
标签: WordPress wordpress教程 wordpress自学 wordpress技术