由Typecho驱动 - 主题WordBook

Typecho调用热门文章、随机文章列表教程

更新:2022-05-26 访问:642

最近开发主题,有很多小伙伴问我怎么实现无插件调用热门文章和随机文章,其实原理很简单,只要懂得基本的数据库操作即可。同样的,当你学会以后,不限于调用热门文章和随机文章,任何文章都能调用。 这里只是用这两个来举个例子,废话不多说,干货开始。

热门文章调用
在function.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, 'parentId' => 0, 'ignoreAuthor' => false));
    }
    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.views', Typecho_Db::SORT_DESC);
        $this->db->fetchAll($select, array($this, 'push'));
    }
}

添加完成之后,在前台可以用如下的方式去写,这种方式好处就在可以更方便的写Html,不用echo出一大段Html。pageSize=5就是输出文章的个数,可以改成你需要的数字。

<?php $this->widget('Widget_Post_hot@hot', 'pageSize=5')->to($hot); ?>
<?php while($hot->next()): ?>
<?php $hot->permalink() ?>//文章链接
<?php $hot->title(); ?>//文章标题
…………//等等
<?php endwhile; ?>

随机文章调用
代码和热门文章的很类似,在function.php里,我们在最后添加以下代码:

class Widget_Post_rand extends Widget_Abstract_Contents
{
    public function __construct($request, $response, $params = NULL)
    {
        parent::__construct($request, $response, $params);
        $this->parameter->setDefault(array('pageSize' => $this->options->commentsListSize, 'parentId' => 0, 'ignoreAuthor' => false));
    }
    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('RAND()');
        $this->db->fetchAll($select, array($this, 'push'));
    }
}

前台的写法也很简洁,同样的pageSize=3就是输出随机文章的个数,可以改成你需要的数字。

<?php $this->widget('Widget_Post_rand@rand', 'pageSize=3')->to($rand); ?>
<?php while($rand->next()): ?>
<?php $rand->permalink() ?>//文章链接
<?php $rand->title(); ?>//文章标题
…………//等等
<?php endwhile; ?>

PHP
总结
这种写法非常接近Typecho原生,使用方法也和Typecho调用某分类下的文章语法一致,掌握后,还可以自己尝试写出最新文章等等~

大家也可以举一反三~