欢迎来到抓润网

wordpress为文章加上字数统计功能_WordPress教程_抓润网

来源: 互联网 日期: 2020-07-16 17:07:42

发现很多网站的文章都有字数统计功能,能计算出当前文章有多少字。觉得这功能不错,对用户体验好,决定把这功能倒腾到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); ?>

(抓润网帝国模板 www.zhuarun.com)


上一篇:wordpress各种web环境下的伪静态规则_WordPress教程_抓润网

下一篇:wordpress中的Pingback和Trackback到底有何区别_WordPress教程_抓润网

  • 在线客服

    点击这里给我发消息 点击这里给我发消息

    官方微信

    仅处理投诉、举报及平台使用问题;
    商品问题请咨询商家客服!

浏览记录