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

发布时间:2020-10-16 16:51:46 作者:小新
来源:亿速云 阅读:193

为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主题添加文章字数和阅读时间的方法大概了解了吗?希望文章内容对大家有所帮助。如果想了解更多相关文章内容,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. 为WordPress文章发布按钮添加确认对话框的方法
  2. WordPress文章标题链接添加正在加载中提示的方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

wordpress %pre 添加文章

上一篇:php7的性能提升有哪些

下一篇:WordPress如何在父页面中显示子页面列表

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》