WordPress在后臺(tái)編輯日志時(shí)編輯框左下角有一個(gè)字?jǐn)?shù)統(tǒng)計(jì),不過(guò)只顯示在后臺(tái),能不能在前臺(tái)也加上文章字?jǐn)?shù)統(tǒng)計(jì)功能呢?研究了一下程序源文件,發(fā)現(xiàn)中文版WP后臺(tái)的字?jǐn)?shù)統(tǒng)計(jì)功能,是通過(guò)wp-content/languages目錄的zh_CN-word-count.js實(shí)現(xiàn)的,就是不知道如何調(diào)用。網(wǎng)上搜了一下,找到兩篇老外給出的代碼:
一、把下面代碼加到主題的functions.php文件中:
- 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;
- }
然后在single.php中希望顯示字?jǐn)?shù)統(tǒng)計(jì)的位置加上:
- Word count: <?php echo count_words($post->post_content); ?>
原文
二、還是將下面代碼加到functions.php文件中,此方法與上面不同的是,還加上了一個(gè)估算的閱讀時(shí)間:
- function show_post_word_count(){
- ob_start();
- the_content();
- $content = ob_get_clean();
- return sizeof(explode(" ", $content));
- }
- 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 ) {
- return est_read_time(true) . "/n/n" . $orig;
- }
- endif;
-
同樣在single.php中希望顯示字?jǐn)?shù)統(tǒng)計(jì)的位置加上:
- The following <?php echo show_post_word_count(); ?> words should take about <?php echo est_read_time(); ?> to read.
可惜上述兩種方法對(duì)漢字統(tǒng)計(jì)無(wú)效,只適合純英文站點(diǎn),網(wǎng)上也沒(méi)發(fā)現(xiàn)與中文博客字?jǐn)?shù)統(tǒng)計(jì)相關(guān)的文章,沒(méi)辦法還是自己折騰一個(gè)吧。
WordPress中文博客文章字?jǐn)?shù)統(tǒng)計(jì)代碼
[reply]
添加方法與上述相同,首先把下面代碼加到functions.php文件中。( 注:HotNews主題加到“//全部結(jié)束”前面 )
- 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;
- }
- }
再把調(diào)用統(tǒng)計(jì)代碼加到自己認(rèn)為適合的位置。
- <?php echo count_words ($text); ?>
經(jīng)測(cè)試對(duì)中文統(tǒng)計(jì)沒(méi)有什么問(wèn)題,英文統(tǒng)計(jì)的是字母。
[/reply]
效果看這篇文章標(biāo)題下面信息欄