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

2023-01-08 0 746
为WordPress主题添加文章字数和阅读时间
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(); ?>

源代码不知出处。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

1、如非特殊说明,本站对本文提供的代码或者素材不拥有任何权利,其版权归原著者拥有。
2、以上提供的代码或者素材均为作者提供和网友推荐收集整理而来,仅供学习和研究使用。
3、如有侵犯你版权的,请来信(邮箱:admin@mail.52muban.com)指出,核实后,本站将立即改正。
4、如有链接无法下载、失效或广告,请点击下面的报错或者联系我们处理!
5、以上资源售价只是赞助,不代表代码或者素材本身价格。收取费用仅维持本站的日常运营所需!
6、本站所有资源、教程、源码,不得用于非法站点及用途,后果自负!本站不为非法站点提供任何服务。

我爱模板网 wordpress教程 为WordPress主题添加文章字数和阅读时间 https://www.52muban.com/29061.html

常见问题
  • 我们承诺演示效果图均和网站一模一样,如有不同,全额退款,并且我们的模板和数据都没有留后门,请放心使用。
查看详情
  • 本站所有源码版权归原作者所有,我爱模板网提供的源码只能用于学习研究,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。
查看详情
发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务

© 2022 我爱模板网- 52muban.com . Powered by WordPress. All rights reserved 网站地图 粤ICP备2020135806号
本站由 腾讯云 提供CDN加速/云服务