Typecho Wiki
每一个作品都值得被记录

Typecho 归档页面显示当前作者/用户的公开文章总数量

Typecho维基君Typecho教程 • 921次浏览 • 发布 2022-04-17 • 更新 2022-04-17
极致加速的V2Ray 助您畅享全球网络 & 搬瓦工VPS最新优惠码

搜索已有解决方案

想要在归档页面显示我发布的总的文章数量。简单搜了一下有下面四篇文章

  • https://zezeshe.com/archives/typecho-author-postsnum.html
  • https://zezeshe.com/archives/typecho-author-allpostsnum.html
  • https://liudm.cn/04.html
  • https://www.dpaoz.com/57

看了之后不免怀疑,好像是真的抄来抄去的……

数据库验证

我这个没写过 php 的今天来试试实现今天这个需求。首先 ssh 进服务器,登录到 mysql 终端页面查看一下规律。

typecho_contentsstatus 字段有两种取值,分别是 publish 代表公开文章,private 私有文章。

mysql> select count(distinct(status)) from typecho_contents;
+-------------------------+
| count(distinct(status)) |
+-------------------------+
|                       2 |
+-------------------------+
1 row in set (0.00 sec)

type 字段取值有 postpage,post 是正常发布文章,page 是独立页面。

mysql> select count(cid) from typecho_contents where type='post';
+------------+
| count(cid) |
+------------+
|        167 |
+------------+
1 row in set (0.00 sec)

过滤一下 status 是 publish 的,刚刚好就是我们需要的值。

mysql> select count(cid) from typecho_contents where status='publish' and type='post';
+------------+
| count(cid) |
+------------+
|        161 |
+------------+
1 row in set (0.00 sec)

过滤一下 status 是 private 的,161+6=167,验证正确。

mysql> select count(cid) from typecho_contents where status='private' and type='post';
+------------+
| count(cid) |
+------------+
|          6 |
+------------+
1 row in set (0.00 sec)

前端验证

打开归档页面,按下 F12 打开浏览器 Inspec 审查功能

var archives = document.getElementById('archives');
var archivesLength = archives.getElementsByTagName('li');
console.log(archivesLength.length);

最终 console.log 输出了 161,和我们从数据库中查到的一致。

20210926211923.png

写 PHP 函数

下面开始编写 php 代码。

可以参考 上面引用的链接第二个 他的代码,不过他的代码最终过滤出来的文章总数是公开的私有的总的文章数量(没有过滤 status 为 publish 的)。

我的代码最终如下,将以下代码添加进主题对应的 functions.php

/**
 * 获取当前用户发布的权限是公开的文章总数量
 */
function allpostnum($id)
{
    $db = Typecho_Db::get();
    $postnum = $db->fetchRow($db->select(array('COUNT(authorId)' => 'allpostnum'))->from('table.contents')->where('table.contents.authorId=?', $id)->where('table.contents.type=?', 'post')->where('table.contents.status=?', 'publish'));
    $postnum = $postnum['allpostnum'];
    return $postnum;
}

前端调用并显示

在主题对应的 page-archives.php 文件适当的位置添加如下代码,我是放在 <h1 class="post-title">$output = '<div id="archives">'; 之间的。

<h2 class="post-title"><?php
        $postNum=allpostnum($this->author->uid);
        echo "目前共计 {$postNum} 篇文章。继续努力。" ?>
        </h2>

最终效果预览

20210926211739.png

end.

广告声明:文内含有的对外跳转链接(包括不限于超链接、二维码、口令等形式),用于传递更多信息,节省甄选时间,结果仅供参考,Typecho.Wiki所有文章均包含本声明。
厂商投放
添加新评论 »