Hexo Stellar 添加全站字数统计 效果预览 在博客页面底部(Footer)显示:
1 共发表 X 篇 Blog · 总计 XXXXX 字
实时统计全站所有文章的总字数。
实现步骤 1. 创建全站字数统计辅助函数 在 themes/stellar/scripts/helpers/ 目录下创建 totalcount.js 文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 hexo.extend .helper .register ('totalcount' , function ( ) { var total = 0 ; var posts = this .site .posts ; posts.forEach (function (post ) { if (post.content ) { var text = post.content .replace (/<[^>]+>/g , '' ); var chinese = (text.match (/[\u4e00-\u9fa5]/g ) || []).length ; var english = (text.match (/[a-zA-Z0-9_\u00C0-\u00FF]+/g ) || []).length ; total += chinese + english; } }); return total; });
编辑 themes/stellar/layout/_partial/main/footer.ejs 文件,在 // footer 部分添加:
1 2 3 4 5 6 7 8 9 10 11 12 el += '<div class="text">' if (content) { el += markdown (content) } el += '<div style="margin-top: 8px; text-align: center;">' el += '<span class="totalcount">共发表 ' + site.posts .length + ' 篇 Blog · </span>' el += '<span class="post-count">总计 ' + totalcount (site) + ' 字</span>' el += '</div>' el += '</div>'
3. 添加 CSS 样式 在 themes/stellar/source/css/_custom.styl 文件末尾添加:
1 2 3 4 5 6 7 8 9 10 11 12 .post-count scrollbar-width : none color : var (--text-p2) .totalcount color : var (--text-p2) .page-footer text-align : center margin : 0 auto width : 100%
4. 重新生成博客 1 2 3 hexo clean hexo generate hexo server
功能说明 字数统计
统计范围 :全站所有文章(posts)
计算规则 :中文字符数 + 英文单词数
显示位置 :页面底部 Footer 区域
显示格式 :共发表 X 篇 Blog · 总计 XXXXX 字
技术细节 1. Helper 函数 使用 hexo.extend.helper.register 注册全局辅助函数:
1 2 3 4 5 hexo.extend .helper .register ('totalcount' , function ( ) { var posts = this .site .posts ; });
2. 文章遍历 遍历所有文章并累加字数:
1 2 3 4 5 6 posts.forEach (function (post ) { if (post.content ) { total += chinese + english; } });
3. 字符匹配
中文 :[\u4e00-\u9fa5] - Unicode 范围
英文 :[a-zA-Z0-9_\u00C0-\u00FF]+ - 单词匹配
性能优化 由于需要遍历所有文章,建议在生成时计算,而不是在页面加载时:
1 2 3 4 5 el += '总计 ' + totalcount (site) + ' 字'
自定义配置 修改显示格式 在 footer.ejs 中修改字符串:
1 2 3 4 5 6 7 el += '<span class="totalcount">Posts: ' + site.posts .length + '</span>' el += '<span class="post-count"> | Words: ' + totalcount (site) + '</span>' el += '<span class="totalcount">文章总数:' + site.posts .length + ' 篇</span>' el += '<span class="post-count"> · 总字数:' + totalcount (site) + ' 字</span>'
修改样式 在 _custom.styl 中调整:
1 2 3 4 .post-count , .totalcount color : var (--text-p1) // 文字颜色 font-size : $fs -13 // 字体大小 font-weight : 500 // 字重
添加千位分隔符 1 2 return total.toLocaleString ();
注意事项
性能考虑 :文章数量多时可能影响生成速度
缓存策略 :建议在生产环境使用缓存
准确性 :代码块中的字符也会被统计
兼容性 :使用 this.site 访问站点数据
效果展示 页面底部显示:
1 2 3 4 © 2024 Kemeow0815 共发表 5 篇 Blog · 总计 12345 字 🦉 本站已安全运行:X 年 X 天 X 小时 X 分钟 X 秒 🦉
参考资料
作者 : Kemeow0815发布日期 : 2026-04-25本文链接 : /2026/04/25/site-wordcount/