今天分享 一个有趣的玩意。那就是给文章增加阅读时间Meta值。之前分享过统计文章字数的,这个可以统计阅读文章大概需要多久的,可以配合使用哦。
- 教程来源:详情
效果图

废话不多说。下面的统计计算阅读时间的相关主代码:
/*-----------------------------------------------------------------------------------*/
# Calculate reaad time
/*-----------------------------------------------------------------------------------*/
if(!function_exists('ie_calculate_reading_time')){
function ie_calculate_reading_time($postID = false, $echo = false) {
$wpm = 250;
if(!$postID){
$postID = get_the_ID();
}
$include_shortcodes = true;
$exclude_images = false;
$tmpContent = get_post_field('post_content', $postID);
$number_of_images = substr_count(strtolower($tmpContent), '<img ');
if ( ! $include_shortcodes ) {
$tmpContent = strip_shortcodes($tmpContent);
}
$tmpContent = strip_tags($tmpContent);
$wordCount = str_word_count($tmpContent);
if ( !$exclude_images ) {
$additional_words_for_images = ie_calculate_images( $number_of_images, $wpm );
$wordCount += $additional_words_for_images;
}
$wordCount = apply_filters( 'ie_filter_wordcount', $wordCount );
$readingTime = ceil($wordCount / $wpm);
// If the reading time is 0 then return it as < 1 instead of 0.
if ( $readingTime < 1 ) {
$readingTime = esc_html__('< 1 min read', 'ie-core');
} elseif($readingTime == 1) {
$readingTime = esc_html__('1 min read', 'ie-core');
} else {
$readingTime = $readingTime.' '.esc_html__('mins read', 'ie-core');
}
if($echo){
echo $readingTime;
} else {
return $readingTime;
}
}
}
因为大多少文章还有图像。我们还需要定义阅读图像的时间,代码如下:
if(!function_exists('ie_calculate_images')){
function ie_calculate_images( $total_images, $wpm ) {
$additional_time = 0;
// For the first image add 12 seconds, second image add 11, ..., for image 10+ add 3 seconds
for ( $i = 1; $i <= $total_images; $i++ ) {
if ( $i >= 10 ) {
$additional_time += 3 * (int) $wpm / 60;
} else {
$additional_time += (12 - ($i - 1) ) * (int) $wpm / 60;
}
}
return $additional_time;
}
}
把上面两段代码复制粘贴到你的主题的funtion.php文件里面。在你想要的位置加入调用下面的调用代码就行了。
<?php echo ie_calculate_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主题统计文章字数也加上吧: