今天分享 一個有趣的玩意。那就是給文章增加閱讀時間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主題統計文章字數也加上吧: