当前位置:首页 > 代码学苑 > 网建教程

wordpress为文章加上字数统计功能

来源:wordpress 作者: 2020-06-17

发现很多网站的文章都有字数统计功能,能计算出当前文章有多少字。觉得这功能不错,对用户体验好,决定把这功能倒腾到wordpress上,谷歌搜了下发现一个老外给出了解决带代码。

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

将以上代码加到主题的functions.php文件中,然后在需要显示字数统计的地方加上以下代码:

<?php echo count_words($post->post_content); ?>

最后本地测试的时候发现此种字数统计代码只对英文有效,对中文完全无效。中文wordpress的字数统计代码如下:

function count_words ($text) {   global $post;   if ( '' == $text ) {      $text = $post->post_content;      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') . '个字';      return $output;   }   }

将以上代码加入到functions.php,然后在需要统计文章字数的地方加上以下代码:

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

猜你喜欢
    无相关信息