把文章数量和阅读时间加到博文中——WordPress美化

2021-11-17 0 698

最近汇站发现一些新媒体网站文章开头有字数和预期阅读时间。这个功能有什么用?我不知道,但是如果别人有,我们可以加一个,那就加吧。

把文章数量和阅读时间加到博文中——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 .= '<span class="word-count">共' . mb_strlen(preg_replace('/\s/','',html_entity_decode(strip_tags($post->post_content))),'UTF-8') .'字</span>';
		return $output;
	}
}

同上继续:

// 阅读时间
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());
}

显示文章字数代码:

<?php echo zm_count_words($text); ?>

显示阅读时间代码:

<?php zm_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(); ?>

 

 

转载请注明:汇站网 » 把文章数量和阅读时间加到博文中——WordPress 美化

收藏 (0)

微信支付 微信扫一扫

支付宝支付 支付宝扫一扫

点赞 (0)

站长资源下载中心-找源码上汇站

常见问题
  • 如果付款后没有弹出下载页面,多刷新几下,有问题联系客服!
查看详情
  • 本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。
查看详情

相关文章

联系官方客服

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