WordPress添加网站文章内容页字数统计代码

wordpress 文章字数统计功能,很简单,而且和 icrosoft Word 统计的字数完全一致。中英文代码统计中都没有出现问题,可以说是一段标准的内容统计代码,简约高效。之所以能有今天的这个方法,还要得益于 wordpress 的强大,既然在后台上可以看到字数的统计功能,那么在前台又为何不能实现?貌似只要知道一点点调用的方法就 OK 了吧?接下来柠檬教大家如何实现!

核心代码

将下面代码复制到 wp 主题的 functions.php 文件里:

//字数统计
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;
}
}

调用代码

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

放在文章配置文件(合适的位置就可以了)测试中文统计正常,英文统计字母。