WordPress教程 给文章页添加文章字数和阅读时间 适用于各种主题

最近看见许多wordpress网站特别是ripro主题美化过的文章页面都有显示文章字数以及所以要的阅读时间,所以今天蓝米兔博客免费分享如何给wordpress的文章页面添加字数统计和推荐阅读时间的功能。没啥实际用处,就是好看而已。

WordPress主题添加文章字数和阅读时间,教程开始:
一、添加文章字数统计:
将以下代码添加到主题函数模板 /functions.php 中:

// 字数统计
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());
}

三、调用代码
显示文章字数代码:

显示阅读时间代码:

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

不过字数统计和阅读时间不是很精确,特别是阅读时间,更是扯淡,默认是按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;
}

调用代码:

到此教程结束。

© 版权声明
THE END
喜欢就支持一下吧
点赞0赞赏 分享
评论 抢沙发

请登录后发表评论