探索建站和运维乐趣

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

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

第一、统计文章字数

    // 字数统计 By LAOBULUO.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 laobuluo.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(); ?>

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

赞(0)
转载保留:老部落 » 给WordPress文章页面添加字数统计和阅读时间效果


关注公众号『老蒋朋友圈』

获取更多建站运营运维新知!
互联网创业、前沿技术......