Typecho自定义组件输出热门文章列表

Typecho自定义组件输出热门文章列表

2023年09月20日 作者头像 作者头像 泽泽社长 编辑

评论

0 Count

Typecho默认没有输出热门文章的组件,所以我们需要自己构建一个,具体如下。

自定义组件

因为Typecho默认没有文章阅读数,所以在构建热门文章时将基于文章评论数进行排序,具体操作就是在主题functions.php填入如下内容

class Widget_Post_Hot extends Widget_Abstract_Contents
{
    public function __construct($request, $response, $params = NULL)
    {
        parent::__construct($request, $response, $params);
        $this->parameter->setDefault(array('pageSize' => $this->options->commentsListSize,));
    }
    public function execute()
    {
        $select  = $this->select()->from('table.contents')
->where("table.contents.password IS NULL OR table.contents.password = ''")
->where('table.contents.status = ?','publish')
->where('table.contents.created <= ?', time())
->where('table.contents.type = ?', 'post')
->limit($this->parameter->pageSize)
->order('table.contents.commentsNum', Typecho_Db::SORT_DESC);
 $this->db->fetchAll($select, array($this, 'push'));
    }
}

这样组件就构建好了,组件里排除了未公开的文章以及加密文章。

调用热门文章

<?php \Widget\Post\Hot::alloc('pageSize=5')->to($hot); ?>
<?php while ($hot->next()): ?>
                   <a href="<?php $hot->permalink(); ?>">
                        <?php $hot->title(); ?>
                    </a>
<?php endwhile; ?>

参数说明

pageSize:为调用文章的数量