Typecho随机文章与同分类下随机文章的实现方法

很久没有整理typecho程序的教程了,今天在网上看到有人想要实现Typecho随机文章的需求,我就去查资料并整理了一下,因为我本人是不怎么使用Typecho建站的,所以一直都没怎么系统的去更新相关的文章,相对于Typecho,我更喜欢WordPress,用户量大是一方面,WordPress的插件,教程很多,编辑器我也觉得好用,可能是因为我本身不喜欢折腾的偏技术的编辑器,可视化好用简单易于操作的编辑器对我来说是最好的了。

在主题functions.php文件中添加如下函数。

class Widget_Post_tongleisuiji 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()
    {
    $adapterName = $this->db->getAdapterName();//兼容非MySQL数据库
    if($adapterName == 'pgsql' || $adapterName == 'Pdo_Pgsql' || $adapterName == 'Pdo_SQLite' || $adapterName == 'SQLite'){
        $order_by = 'RANDOM()';
    }else{
        $order_by = 'RAND()';
    }   
$select  = $this->select()->from('table.contents')
->join('table.relationships', 'table.contents.cid = table.relationships.cid');
if($this->parameter->mid>0){
$select->where('table.relationships.mid = ?', $this->parameter->mid);
}
$select->where('table.contents.cid <> ?', $this->parameter->cid)
->where("table.contents.password IS NULL OR table.contents.password = ''")
->where('table.contents.type = ?', 'post')
->limit($this->parameter->pageSize)
->order($order_by);
$this->db->fetchAll($select, array($this, 'push'));
    }
}

在主题需要的地方调用如下内容即可随机输出多篇文章,样式需要自行美化。

<?php 
$mid='';//此参数为空时为随机文章,为分类mid时则为当前分类下的随机文章
$cid=0;//此参数填写当前文章的cid即可在随机文章时不输出当前文章
$size=5;//随机输出文章的数量
$this->widget('Widget_Post_tongleisuiji@suiji', 'mid='.$mid.'&pageSize='.$size.'&cid='.$cid)->to($to);?>
<?php if($to->have()): ?>
<?php while($to->next()): ?>
<!--文章内容开始-->
<?php $to->title(); ?>
<?php $to->excerpt(150, '...'); ?>
<?php $to->permalink() ?>
<!--文章内容结束-->
<?php endwhile; ?>
<?php endif; ?>

其余的内容,可以参考文章《无插件实现Typecho网站随机文章调用的方法

👋 感谢您的观看!

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享