WordPress如何添加文章字数统计和预计阅读时间?

有些新媒体网站的文章开头,有字数统计和该文的预期阅读时间。

一、添加WordPress文章字数统计代码

将以下代码添加到主题中的最后几个functions.php文件中 ?> 之前 ▼

//字数统计
function count_words ($text) {
global $post;
if ( '' == $text ) {
$text = $post->post_content;
if (mb_strlen($output, 'UTF-8') < mb_strlen($text, 'UTF-8')) $output .= '本文《' . get_the_title() .'》共' . mb_strlen(preg_replace('/\s/','',html_entity_decode(strip_tags($post->post_content))),'UTF-8') . '个字';
return $output;
}

二、为WordPress预计阅读时间

将以下代码添加到主题中的最后几个functions.php文件中 ?>

保存之后,你可以在WordPress文章内容的开头自动显示“预计阅读时间x分钟”▼

function lmsim_read_time($content){
$text = trim(strip_tags( get_the_content()));
$text_num = mb_strlen($text, 'UTF-8');
$read_time = ceil($text_num/400);
$content = '<div class="read-time">系统预计阅读时间 <span>' . $read_time . '</span> 分钟</div>' . $content;
return $content;
}
add_filter ( 'the_content', 'lmsim_read_time');

在测试之后,发现上面代码统计中的单词数有一些错误,这些错误,超出了实际错误

三、优化预期阅读时间

将以下代码添加到主题中的最后几个functions.php文件中 ?> 之前 ▼

//字数和预计阅读时间统计
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/400);
$output .= '本文《' . get_the_title() .'》共' . $text_num . '个字,系统预计阅读时间或需' . $read_time . '分钟。';
return $output;
}

然后,将调用统计代码添加到single.php文件中的适当位置。

<?php echo count_words_read_time(); ?>

四、预计阅读时间码优化之前和之后比较

在陈沩亮测试之后,当字数小于或等于400时,即当预计阅读时间小于或等于1分钟时。

但是,如果它超过400,它将是有偏差的。

(ceil() 函数)是什么?

ceil() 函数向上舍入到最接近的整数。

这意味着返回不小于x的下一个整数。

如果x具有小数部分,则ceil() 返回的类型仍然是float,因为float的范围通常大于integer

例子

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注