顯示文章字?jǐn)?shù)和閱讀時間,這功能有什么用呢,我也不知道,不過有用戶說人家有我們能不能也加一個,那就加吧。下面由WordPress教程欄目給大家介紹為wordpress主題添加文章字?jǐn)?shù)和閱讀時間的方法。
為WordPress主題添加文章字?jǐn)?shù)和閱讀時間為WordPress主題添加文章字?jǐn)?shù)和閱讀時間
具體代碼這里也分享一下:
文章字?jǐn)?shù)統(tǒng)計
//?字?jǐn)?shù)統(tǒng)計 function?zm_count_words?($text)?{ global?$post; if?(?''?==?$text?)?{ $text?=?$post->post_content; if?(mb_strlen($output,?'UTF-8')?共'?.?mb_strlen(preg_replace('/s/','',html_entity_decode(strip_tags($post->post_content))),'UTF-8')?.'字'; return?$output; } }
代碼添加到當(dāng)前主題函數(shù)模板 functions.php 中。
文章閱讀時間
//?閱讀時間 function?zm_get_reading_time($content)?{ $zm_format?=?'<span>閱讀時間%min%分%sec%秒</span>'; $zm_chars_per_minute?=?300;?//?估算1分種閱讀字?jǐn)?shù) ? $zm_format?=?str_replace('%num%',?$zm_chars_per_minute,?$zm_format); $words?=?mb_strlen(preg_replace('/s/','',html_entity_decode(strip_tags($content))),'UTF-8'); ? $minutes?=?floor($words?/?$zm_chars_per_minute); $seconds?=?floor($words?%?$zm_chars_per_minute?/?($zm_chars_per_minute?/?60)); return?str_replace('%sec%',?$seconds,?str_replace('%min%',?$minutes,?$zm_format)); } ? function?zm_reading_time()?{ echo?zm_get_reading_time(get_the_content()); }
代碼添加到當(dāng)前主題函數(shù)模板 functions.php 中。
調(diào)用文章字?jǐn)?shù)和閱讀時間代碼
顯示文章字?jǐn)?shù)代碼:
<?php echo zm_count_words($text); ?>
顯示閱讀時間代碼:
<?php zm_reading_time(); ?>
將上述調(diào)用代碼加到當(dāng)前主題正文模板的適當(dāng)位置即可。
不過字?jǐn)?shù)統(tǒng)計和閱讀時間不是很精確,特別是閱讀時間,更是扯淡,默認(rèn)是按CCTV廣播員語速定的。
寫完這篇文章,發(fā)現(xiàn)網(wǎng)上有更簡潔的代碼,區(qū)別是上面的代碼精確到秒,下面的代碼只估算到分。
function?count_words_read_time?()?{ global?$post; $text_num?=?mb_strlen(preg_replace('/s/','',html_entity_decode(strip_tags($post->post_content))),'UTF-8'); $read_time?=?ceil($text_num/300);?//?修改數(shù)字300調(diào)整時間 $output?.=?'本文共計'?.?$text_num?.?'個字,預(yù)計閱讀時長'?.?$read_time??.?'分鐘。'; return?$output; }
調(diào)用代碼:
<?php echo count_words_read_time(); ?>
? 版權(quán)聲明
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載。
THE END