1 一、添加WordPress文章字數(shù)統(tǒng)計代碼
有些新媒體網(wǎng)站的文章開頭,有字數(shù)統(tǒng)計和該文的預(yù)期閱讀時間。
將以下代碼添加到主題中的最后幾個functions.php文件中 ?>
之前?▼
//字數(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 .= '本文《' . get_the_title() .'》共' . mb_strlen(preg_replace('/\s/','',html_entity_decode(strip_tags($post->post_content))),'UTF-8') . '個字'; return $output; }
將以下代碼添加到主題中的最后幾個functions.php文件中 ?>
保存之后,你可以在WordPress文章內(nèi)容的開頭自動顯示“預(yù)計閱讀時間x分鐘”▼
function lmsim_read_time($content){ $text = trim(strip_tags( get_the_content())); $text_num = mb_strlen($text, 'UTF-8'); $read_time = ceil($text_num/400); $content = '<div class="read-time">系統(tǒng)預(yù)計閱讀時間 <span>' . $read_time . '</span> 分鐘</div>' . $content; return $content; } add_filter ( 'the_content', 'lmsim_read_time');
在測試之后,發(fā)現(xiàn)上面代碼統(tǒng)計中的單詞數(shù)有一些錯誤,這些錯誤,超出了實際錯誤
將以下代碼添加到主題中的最后幾個functions.php文件中 ?>
之前?▼
//字數(shù)和預(yù)計閱讀時間統(tǒng)計 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/400); $output .= '本文《' . get_the_title() .'》共' . $text_num . '個字,系統(tǒng)預(yù)計閱讀時間或需' . $read_time . '分鐘。'; return $output; }
然后,將調(diào)用統(tǒng)計代碼添加到single.php文件中的適當位置。
<?php echo count_words_read_time(); ?>
在我們測試之后,當字數(shù)小于或等于400時,即當預(yù)計閱讀時間小于或等于1分鐘時。
但是,如果它超過400,它將是有偏差的。
ceil()?函數(shù)向上舍入到最接近的整數(shù)。
這意味著返回不小于x的下一個整數(shù)。
如果x具有小數(shù)部分,則ceil()?返回的類型仍然是float
,因為float
的范圍通常大于integer。
例子
希望我們網(wǎng)站( https://www.wordpressx.com/ ) 分享的《WordPress如何添加文章字數(shù)統(tǒng)計和預(yù)計閱讀時間?》,對您有幫助。