WordPress同时统计文章中文和英文单词数

WordPress并没有内置同时统计中文和英文单词字数的函数,网上能找到的代码,或是仅统计英文单词,不能统计中文,或者可以统计中文,但英文按字母而非单词统计。虽然我们不是英文站,但有时文章中会有些英文单词,这样统计就不准确了。

下面的代码可以同时统计文章中文和英文单词数,并相加输出。

自定义函数:

function word_count() {
	$post_content = get_post_field( 'post_content', get_the_ID() );
	$striped_tags = strip_tags( $post_content );
	// 统计中文
	$zh_words = preg_match_all( '/[\x{4e00}-\x{9fa5}]/u', $striped_tags, $matches );
	// 统计英文
	$en_words = str_word_count( $striped_tags );
	// 合计
	$total_words = $zh_words + $en_words;
	return $total_words . ' 字';
}

输出:

<?php echo word_count(); ?>

给TA赏糖
共{{data.count}}人
人已赏糖
技术分享

禁止WordPress目录枚举

2024-12-1 17:01:24

技术分享

微信分付怎么开通?详细解析快速上手指南

2024-12-1 19:05:12

0 条回复 A文章作者 M管理员
技术宅评论
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索