發(fā)現(xiàn)很多網(wǎng)站的文章都有字數(shù)統(tǒng)計功能,能計算出當前文章有多少字,。覺得這功能不錯,,對用戶體驗好,決定把這功能倒騰到wordpress上,,谷歌搜了下發(fā)現(xiàn)一個老外給出了解決帶代碼,。
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文件中,,然后在需要顯示字數(shù)統(tǒng)計的地方加上以下代碼:
<?php echo count_words($post->post_content); ?>
最后本地測試的時候發(fā)現(xiàn)此種字數(shù)統(tǒng)計代碼只對英文有效,,對中文完全無效,。中文wordpress的字數(shù)統(tǒng)計代碼如下:
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,,然后在需要統(tǒng)計文章字數(shù)的地方加上以下代碼:
<?php echo count_words ($text); ?>