为WordPress添加文章字数统计

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

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

  1.  count_words(){
  2.      = 0;
  3.      = (, , );
  4.      = (, );
  5.     (=0; < ();++)
  6.      {
  7.          ((, []))
  8.             ++;
  9.     }
  10.      ;
  11. }

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

  1. Word : <?php  count_words(->post_content); ?>

原文

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

  1.  show_post_word_count(){
  2. ob_start();
  3. the_content();
  4.  = ob_get_clean();
  5.  sizeof((, ));
  6. }
  7.  (!function_exists(\’est_read_time\’)):
  8.  est_read_time(  = false) {
  9.  = ((get_the_content()), -2);
  10.  = ( / 250);
  11.  = ( / 150);
  12.  ( <= 150) {
  13.  = __();
  14. }  {
  15.  = sprintf(__(), , );
  16. }
  17.  ;
  18. }
  19. ;
  20.  (!function_exists(\’est_the_content\’)):
  21.  est_the_content(  ) {
  22.  est_read_time(true) .  . ;
  23. }
  24. ;

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

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

原文

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

WordPress中文博客文章字数统计代码

添加方法与上述相同,首先把下面代码加到functions.php文件中。( 注:HotNews主题加到“//全部结束”前面 )

  1.  count_words () {
  2.  ;
  3.  (  ==  ) {
  4.     = ->post_content;
  5.     (mb_strlen(, \’UTF-8\’) < mb_strlen(, \’UTF-8\’))  .= \’本文共\’ . mb_strlen(preg_replace(\’/\\s/\’,,html_entity_decode((->post_content))),\’UTF-8\’) . \’个字\’;
  6.     ;
  7. }
  8. }

再把调用统计代码加到自己认为适合的位置。

  1. <?php  count_words (); ?>

经测试对中文统计没有什么问题,英文统计的是字母。

效果看这篇文章标题下面信息栏

这个评论可见功能参见:WordPress博客评论可见实现方法

    © 版权声明
    THE END
    喜欢就支持一下吧
    点赞0 分享
    评论 抢沙发

    请登录后发表评论

      暂无评论内容