为WordPress添加文章字数统计的方法

2019-02-19 16:53:30王冬梅

WordPress在后台编辑日志时编辑框左下角有一个字数统计,不过只显示在后台,能不能在前台也加上文章字数统计功能呢?研究了一下程序源文件,发现中文版WP后台的字数统计功能,是通过wp-contentlanguages目录的zh_CN-word-count.js实现的,就是不知道如何调用。网上搜了一下,找到两篇老外给出的代码:

一、把下面代码加到主题的functions.php文件中:

  1. function count_words($str){ $words = 0;
  2. $str = eregi_replace(" +", " ", $str); $array = explode(" ", $str);
  3. for($i=0;$i < count($array);$i++) {
  4. if (eregi("[0-9A-Za-zÀ-ÖØ-öø-ÿ]", $array[$i])) $words++;
  5. } return $words;
  6. }

然后在single.php中希望显示字数统计的位置加上:

  1. Word count: <?php echo count_words($post->post_content); ?>

原文

二、还是将下面代码加到functions.php文件中,此方法与上面不同的是,还加上了一个估算的阅读时间:

  1. // Custom functions // START : Show word count
  2. function show_post_word_count(){ ob_start();
  3. the_content(); $content = ob_get_clean();
  4. return sizeof(explode(" ", $content)); }
  5. // END : Show word count // START : Estimated reading time
  6. if (!function_exists('est_read_time')): function est_read_time( $return = false) {
  7. $wordcount = round(str_word_count(get_the_content()), -2); $minutes_fast = ceil($wordcount / 250);
  8. $minutes_slow = ceil($wordcount / 150); if ($wordcount <= 150) {
  9. $output = __("< 1 minute"); } else {
  10. $output = sprintf(__("%s - %s minutes"), $minutes_fast, $minutes_slow); }
  11. echo $output; }
  12. endif; if (!function_exists('est_the_content')):
  13. function est_the_content( $orig ) { // Prepend the reading time to the post content
  14. return est_read_time(true) . "nn" . $orig; }
  15. endif; // END : Estimated reading time

同样在single.php中希望显示字数统计的位置加上:

  1. The following <?php echo show_post_word_count(); ?> words should take about <?php echo est_read_time(); ?> to read.

可惜上述两种方法对汉字统计无效,只适合纯英文站点,网上也没发现与中文博客字数统计相关的文章,没办法还是自己折腾一个吧。