Typecho 获取网站统计数据

下面的代码放在主题的 functions.php 文件中,在每个页面都能调用

获取文章数量

获取文章数量,不包含草稿和未公开的文章

function postCount() {
    $db = Typecho_Db::get();
    // 查询出文章数量并转换为数组
    $count = $db->fetchRow($db->select('COUNT(*)')->from('table.contents')->where('type = ?', 'post')->where('status = ?', 'publish'));
    // 返回文章数量
    return $count['COUNT(*)'];
}

Typecho 的文章和独立页面都存储在 Typecho 数据库的 typecho_contents 表中,使用 Typecho 提供的 API 查询时可以不需要加 typecho 前缀。typecho_contents 表中有个 type 字段是用来存储内容类型的,post 是普通文章,page 是独立页面。status 字段是存储文章状态,publish 是公开的,draft 是草稿。如果要获取独立页面数量可以把 where('type = ?', 'post') 换为 where('type = ?', 'page') ,如果要获取所有公开、未公开、和草稿文章数量可以直接把 where('status = ?', 'publish') 方法删除。

获取评论数量

function commentsCount() {
    $db = Typecho_Db::get();
    // 查询出评论数量并转换为数组
    $count = $db->fetchRow($db->select('COUNT(*)')->from('table.comments')->where('status = ?', 'approved'));
    // 返回评论数量
    return $count['COUNT(*)'];
}

获取分类数量

function categoryCount() {
    $db = Typecho_Db::get();
    // 查询出分类数量并转换为数组
    $count = $db->fetchRow($db->select('COUNT(*)')->from('table.metas')->where('type = ?', 'category'));
    // 返回分类数量
    return $count['COUNT(*)'];
}

获取标签数量

function tagCount() {
    $db = Typecho_Db::get();
    $count = $db->fetchRow($db->select('COUNT(*)')->from('table.metas')->where('type = ?', 'tag'));
    return $count['COUNT(*)'];
}

获取总点赞数量

function agreeCount() {
    $db = Typecho_Db::get();
    // 对文章表的 agree 字段进行求和并把查询出的结果转换为数组
    $count = $db->fetchRow($db->select('SUM(agree) AS agreeCount')->from('table.contents'));
    // 返回总点赞数
    return $count['agreeCount'];
}

获取评论数量排名前 5 的 5 篇文章

function top5CommentPost() {
    $db = Typecho_Db::get();
    // 查询出 5 条评论数最大的文章,按照评论数从大到小排序,然后把查询出的数据转换为数组
    $top5Post = $db->fetchAll($db->select()->from('table.contents')->where('type = ?', 'post')->where('status = ?', 'publish')->order('commentsNum', Typecho_Db::SORT_DESC)->offset(0)->limit(5));
    // 用来存储文章信息的数组
    $postList = array();
    foreach ($top5Post as $post) {
        // 使用 Typecho 提供的 API 获取每篇文章的链接地址
        $post = Typecho_Widget::widget('Widget_Abstract_Contents')->filter($post);
        // 把文章标题、链接、点赞数加入数组
        array_push($postList, array(
            'title' => $post['title'],
            'link' => $post['permalink'],
            'commentsNum' => $post['commentsNum']
        ));
    }
    // 返回 5 篇文章的标题、链接、点赞数
    return $postList;
}

获取各分类的文章数量

function categoryPostCount() {
    $db = Typecho_Db::get();
    // 查询出每个分类的文章数量并转换为数组
    $count = $db->fetchAll($db->select('name', 'count')->from('table.metas')->where('type = ?', 'category'));
    // 如果没有查询到数据就返回空数组
    if (count($count) < 1) {
        return array();
    }
    // 返回每个分类的文章数量
    return $count;
}
(0)

相关推荐