给WordPress文章页面添加字数统计和阅读时间效果

我们是否有不少的网友在看到有些博客阅读文章的时候比较人性化的显示这篇文章的字数统计,以及预估这篇文章需要阅读多长时间。如果我们也有需要的话,可以在自己主题中添加对应的代码,无需使用插件直接可以使用到的。

第一、统计文章字数

    // 字数统计 By IMOTAO.COM
    function cnwper_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 文件中。

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

在需要的位置调用代码即可。

第二、统计预估阅读时间

// 统计预估阅读时间 By imotao.com
    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;
    }

同样添加到当前Functions.php主题设置文件中。

<?php echo count_words_read_time(); ?>

然后在需要的模板位置调用。

原创文章,作者:陌涛,如若转载,请注明出处:https://imotao.com/3388.html

(0)
陌涛的头像陌涛
上一篇 2020年7月20日 上午10:30
下一篇 2020年7月20日

相关推荐

发表回复

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

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据