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

教程:如何给文章增加阅读时间废话不多说。下面的统计计算阅读时间的相关主代码:

The WordPress Toolbox
Unlimited Downloads: 500,000+ WordPress Themes, Plugins, Templates & Design Assets

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

DOWNLOAD NOW

/*-----------------------------------------------------------------------------------*/# 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(); ?>

就这么简单。有兴趣的朋友可以试试给自己的文章新增这么一个小功能。

发表回复