折腾了下Typecho主题添加文章字数统计代码,顺便记录一下
打开主题目录下的 functions.php
文件,添加以下代码:
function allOfCharacters() {
$chars = 0;
$db = Typecho_Db::get();
$select = $db ->select('text')->from('table.contents');
$rows = $db->fetchAll($select);
foreach ($rows as $row) { $chars += mb_strlen(trim($row['text']), 'UTF-8'); }
$unit = '';
if($chars >= 10000) { $chars /= 10000; $unit = '万'; }
else if($chars >= 1000) { $chars /= 1000; $unit = '千'; }
$out = sprintf('%.2lf %s',$chars, $unit);
return $out;
}
随后,前往 footer.php
或者是页脚部分中添加显示代码皆可
<span> ✏️文章共有 <?php echo allOfCharacters(); ?>字</span>
刷新查看是否生效