WD1X.COM - 问答一下,轻松解决,电脑应用解决专家
主板显卡CPU内存显示器
硬盘维修显卡维修显示器维修
注册表系统命令DOS命令Win8
存储光存储鼠标键盘
内存维修打印机维修
WinXPWin7Win11Linux
硬件综合机箱电源散热器手机数码
主板维修CPU维修键盘鼠标维修
Word教程Excel教程PowerPointWPS
网络工具系统工具图像工具
数据库javascript服务器
PHP教程CSS教程XML教程

为WordPress添加文章字数统计

更新时间:2012-10-03 10:50 作者:佚名点击:

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

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

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

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

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

原文

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

 
  1. // Custom functions   
  2. // START : Show word count   
  3. function show_post_word_count(){   
  4. ob_start();   
  5. the_content();   
  6. $content = ob_get_clean();   
  7. return sizeof(explode(" "$content));   
  8. }   
  9. // END : Show word count   
  10. // START : Estimated reading time   
  11. if (!function_exists('est_read_time')):   
  12. function est_read_time( $return = false) {   
  13. $wordcount = round(str_word_count(get_the_content()), -2);   
  14. $minutes_fast = ceil($wordcount / 250);   
  15. $minutes_slow = ceil($wordcount / 150);   
  16. if ($wordcount <= 150) {   
  17. $output = __("< 1 minute");   
  18. else {   
  19. $output = sprintf(__("%s - %s minutes"), $minutes_fast$minutes_slow);   
  20. }   
  21. echo $output;   
  22. }   
  23. endif;   
  24. if (!function_exists('est_the_content')):   
  25. function est_the_content( $orig ) {   
  26. // Prepend the reading time to the post content   
  27. return est_read_time(true) . "\n\n" . $orig;   
  28. }   
  29. endif;   
  30. // 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.  

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

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

[reply]

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

  1. //字数统计   
  2. function count_words ($text) {   
  3. global $post;   
  4. if ( '' == $text ) {   
  5.    $text = $post->post_content;   
  6.    if (mb_strlen($output, 'UTF-8') < mb_strlen($text, 'UTF-8')) $output .= '本文共' . mb_strlen(preg_replace('/\s/','',html_entity_decode(strip_tags($post->post_content))),'UTF-8') . '个字';   
  7.    return $output;   
  8. }   
  9. }  

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

  1. <?php echo count_words ($text); ?>  

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

[/reply]

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

顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------
你可能感兴趣的内容