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

WordPress评论208阅读模式

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

下面的代码可以同时统计文章中文和英文单词数,并相加输出。文章源自知更鸟-https://zmingcx.com/wordpress-count-chinese-and-english-words.html

自定义函数:

function zm_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 zm_word_count(); ?>

 文章源自知更鸟-https://zmingcx.com/wordpress-count-chinese-and-english-words.html 文章源自知更鸟-https://zmingcx.com/wordpress-count-chinese-and-english-words.html

本站文章大部分始于原创,用于个人学习记录,可能对您有所帮助,仅供参考!

weinxin
我的微信
版权声明
本站原创文章转载请注明文章出处及链接,谢谢合作!
 
知更鸟
匿名

发表评论

匿名网友
:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

拖动滑块以完成验证