今天小編逛了下鳳凰網,發現鳳凰網的文章有個字數統計,能計算出當前文章有多少字並且現出來,還給出了閱讀時間提示。小編覺得這功能不錯,對使用者體驗好,決定把這功能倒騰到 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); ?>

小編在本地測試的時候發現此種字數統計程式碼只對英文有效,對中文完全無效。中文 WordPress 的字數統計程式碼如下:

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); ?>

即可。