WordPress在后臺編輯日志時編輯框左下角有一個字數統計,不過只顯示在后臺,能不能在前臺也加上文章字數統計功能呢?研究了一下程序源文件,發現中文版WP后臺的字數統計功能,是通過wp-content\languages目錄的zh_CN-word-count.js實現的,就是不知道如何調用。網上搜了一下,找到兩篇老外給出的代碼:
一、把下面代碼加到主題的functions.php文件中:
- functioncount_words($str){
- $words= 0;
- $str=eregi_replace(" +"," ",$str);
- $array=explode(" ",$str);
- for($i=0;$i
- {
- if(eregi("[0-9A-Za-zÀ-ÖØ-öø-ÿ]",$array[$i]))
- $words++;
- }
- return$words;
- }
然后在single.php中希望顯示字數統計的位置加上:
- Word count: <?php echo count_words($post->post_content); ?>
原文
二、還是將下面代碼加到functions.php文件中,此方法與上面不同的是,還加上了一個估算的閱讀時間:
- // Custom functions
- // START : Show word count
- function show_post_word_count(){
- ob_start();
- the_content();
- $content = ob_get_clean();
- return sizeof(explode(" ", $content));
- }
- // END : Show word count
- // START : Estimated reading time
- if (!function_exists('est_read_time')):
- function est_read_time( $return = false) {
- $wordcount = round(str_word_count(get_the_content()), -2);
- $minutes_fast = ceil($wordcount / 250);
- $minutes_slow = ceil($wordcount / 150);
- if ($wordcount <= 150) {
- $output = __("< 1 minute");
- } else {
- $output = sprintf(__("%s - %s minutes"), $minutes_fast, $minutes_slow);
- }
- echo $output;
- }
- endif;
- if (!function_exists('est_the_content')):
- function est_the_content( $orig ) {
- // Prepend the reading time to the post content
- return est_read_time(true) . "\n\n" . $orig;
- }
- endif;
- // END : Estimated reading time
同樣在single.php中希望顯示字數統計的位置加上:
- The following <?php echo show_post_word_count(); ?> words should take about <?php echo est_read_time(); ?> to read.
可惜上述兩種方法對漢字統計無效,只適合純英文站點,網上也沒發現與中文博客字數統計相關的文章,沒辦法還是自己折騰一個吧。
WordPress中文博客文章字數統計代碼
添加方法與上述相同,首先把下面代碼加到functions.php文件中。( 注:HotNews主題加到“//全部結束”前面 )
- //字數統計
- 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); ?>
效果看這篇文章標題下面信息欄