2025年02月15日 建站教程
wordpress如何获取文章字数和阅读时间,下面web建站小编给大家详细介绍一下如何实现代码!
找到当前主题函数模板functions.php中添加以下代码:
// 字数统计 function get_words_count($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; } }
模板中调用文章字数
<?php echo get_words_count($text); ?>
// 阅读时间 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 get_reading_time() { echo zm_get_reading_time(get_the_content()); }
模板中调用文章阅读时间
<?php get_reading_time(); ?>
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(); ?>
本文链接:http://so.lmcjl.com/news/23204/