A-A+
wordpress为文章添加字数统计的功能
今天在逛博友的博客时,发现一个有趣的功能,就是每一篇文章都可以统计出有多少个字数并且显示出现,感觉这个功能对于用户的体验很好,不仅对于用户来说,这个功能较细微,而且对于管理员自己来说,每一篇文章自己码了多少字,也能清晰的看到了,决定也来折腾折腾自己的 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); ?>
中文文章字数统计代码如下:
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); ?>
再来预览一下前台的文章是否已经添加了文章统计字数的效果了,体验效果很棒的,你也来尝试一下吧。