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