首页 » 收集 » 正文内容
Typecho调用热门文章、随机文章列表教程
寻梦xunm| 763| 收集
3年前
超过1207天 温馨提示
本文最后更新于2021年05月31日,已超过1207天没有更新,若内容或图片失效,请留言反馈。

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

在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; ?>

总结

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

文章来源于:https://blog.zwying.com/archives/40.html

0 赞 or 打赏
喜欢就打赏一点
微信 支付宝
隐私
Q Q:1340326824
邮箱:vipshiyi@qq.com
QQ群:422720328

我的音乐

微博客-专为自己编写开发的源码