教程:如何给文章增加阅读时间

添加文章的阅读时间。

来源于:

https://www.iesay.com/calculate-post-reading-time.html

今天分享 一个有趣的玩意。那就是给文章增加阅读时间Meta值。在我的新主题IEBLOG主题中我们集成了这个功能。显示效果见图

教程:如何给文章增加阅读时间

废话不多说。下面的统计计算阅读时间的相关主代码:

/*-----------------------------------------------------------------------------------*/
# 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(); ?>
软件
0 条回复 A 作者 M 管理员
    所有的伟大,都源于一个勇敢的开始!
欢迎您,新朋友,感谢参与互动!欢迎您 {{author}},您在本站有{{commentsCount}}条评论