大发有旧文《WordPress 估算文章阅读时间》,实际应用了一下,觉得:1、用平均阅读时间不很准确;2、只能显示分钟,不科学。于是改良如下:
//估算文章阅读时间
//获取文章长度
function fa_get_postlength(){
global $post;
//注:如文中用了某些特殊插件导致出现大量特殊字符,建议用 wp_strip_all_tags。
return strlen( strip_shortcodes(strip_tags(apply_filters('the_content', $post->post_content))) );
}

//获取图片张数
function fa_get_post_img_count(){
global $post;
preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', $post->post_content, $strResult, PREG_PATTERN_ORDER);
return count($strResult[1]);
}

//增加判断并输出小时、分钟和秒数功能
function Sec2Time($time){
if(is_numeric($time)){
$value = array(
"years" => 0, "days" => 0, "hours" => 0,
"minutes" => 0, "seconds" => 0,
);
if($time >= 31556926){
$value["years"] = floor($time/31556926);
$time = ($time%31556926);
}
if($time >= 86400){
$value["days"] = floor($time/86400);
$time = ($time%86400);
}
if($time >= 3600){
$value["hours"] = floor($time/3600);
$time = ($time%3600);
}
if($time >= 60){
$value["minutes"] = floor($time/60);
$time = ($time%60);
}
$value["seconds"] = floor($time);
if($value["hours"] != 0) {
$t= $value["hours"] ."h". $value["minutes"] ."m".$value["seconds"]."s";
}
if($value["hours"] == 0 && $value["minutes"] != 0) {
$t= $value["minutes"] ."m".$value["seconds"]."s";
if($value["seconds"] == 0) {
$t= $value["minutes"] ."m";
}
}
if($value["hours"] == 0 && $value["minutes"] == 0 && $value["seconds"] !=0) {
$t= $value["seconds"]."s";
}
if($value["hours"] == 0 && $value["minutes"] == 0 && $value["seconds"] ==0) {
$t= "1s";
}
Return $t;
}else{
return (bool) FALSE;
}
}

//计算阅读时间,以秒为单位
function fa_get_post_readtime(){
global $post;
$all = fa_get_postlength() / 40 + fa_get_post_img_count();
return Sec2Time($all);
}

在循环内使用 <?php echo fa_get_post_readtime(); ?> 调用。