WordPress 前台编辑器加上字数统计功能

WordPress在后台编辑文章时编辑框左下角有一个字数统计,不过只显示在后台,能不能在前台也加上文章字数统计功能呢 wordpress WordPress在后台编辑文章时编辑框左下角有一个字数统计,不过只显示在后台,能不能在前台也加上文章字数统计功能呢?研究了一下程序源文件,发现中文版WP后台的字数统计功能,是通过w...

WordPress在后台编辑文章时编辑框左下角有一个字数统计,不过只显示在后台,能不能在前台也加上文章字数统计功能呢

Wordpress 前台编辑器加上字数统计功能
wordpress

WordPress在后台编辑文章时编辑框左下角有一个字数统计,不过只显示在后台,能不能在前台也加上文章字数统计功能呢?研究了一下程序源文件,发现中文版WP后台的字数统计功能,是通过wp-contentlanguages目录的zh_CN-word-count.js实现的,就是不知道如何调用。网上搜了一下,找到两篇老外给出的代码:

代码一、把下面代码加到主题的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中希望显示字数统计的位置加上:

Word count: <?php echo count_words($post->post_content); ?>

代码二、还是将下面代码加到functions.php文件中,此方法与上面不同的是,还加上了一个估算的阅读时间:

// Custom functions
// START : Show word count
function show_post_word_count(){
ob_start();
the_content();
$content = ob_get_clean();
return sizeof(explode(" ", $content));
}
// END : Show word count
// START : Estimated reading time
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 ) {
// Prepend the reading time to the post content
return est_read_time(true) . "nn" . $orig;
}
endif;
// END : Estimated reading time

同样在single.php中希望显示字数统计的位置加上:

The following <?php echo show_post_word_count(); ?> words should take about <?php echo est_read_time(); ?> to read.

可惜上述两种方法对汉字统计无效,只适合纯英文站点,网上也没发现与中文博客字数统计相关的文章,没办法还是自己折腾一个吧。

WordPress中文博客文章字数统计代码

添加方法与上述相同,首先把下面代码加到functions.php文件中。( 注:HotNews主题加到“//全部结束”前面 )

//字数统计
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;
}
}

再把调用统计代码加到自己认为适合的位置。

<?php echo count_words ($text); ?>

经测试对中文统计没有什么问题,英文统计的是字母。

给TA打赏
共{{data.count}}人
人已打赏
wordpress教程

给你的WordPress网站添加固定的百度分享按钮

2023-2-16 23:48:11

wordpress教程

WordPress首页排除特定分类文章

2023-2-16 23:48:13

【腾讯云】11.11云上盛惠!云服务器首年1.8折起,买1年送3个月!
11.11云上盛惠!海量产品·轻松上云!云服务器首年1.8折起,买1年送3个月!超值优惠,性能稳定,让您的云端之旅更加畅享。
查看更多相关信息>>
在线咨询
站长

(工作日 10:00 - 22:30 为您服务)

2026-07-08 04:50:08

您好,无论是售前、售后、意见建议……均可通过联系工单与我们取得联系。

猜你想问:

  • 购买的模板免费包安装吗?

  • 这个演示地址有吗?

  • 购买vip会员可以下载哪些模板?

您的留言我们已经收到,我们将会尽快跟您联系!
取消
立即选择任一渠道联系我们