LoadSystem
MoeOS(2023.3.27)

工匠的骄傲和喜悦
The Pride & Joy of an Artisan
Typecho随机文章与同分类下随机文章的实现
7 条讨论

在制作Typecho主题时,有的时候会想弄个随机推荐文章的功能,所以我就简单弄了个函数,可以随机输出n篇文章,同时追加一些参数还可以输出当前文章分类下的随机文章,具体如下:

>
函数部分

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

>
拓展内容

在文章页面下,调用这个函数时可以这样填写参数

$cid=$this->cid;//这样设置下cid,随机推荐文章时就不会与当前文章重复了
$mid=$this->categories[0]['mid'];//这样设置函数即可获得文章的第一个分类,然后随机输出这个分类下的文章
$size=5;

有的时候我们其他页面和文章页面都是在同一处输出随机文章,此时我们就可以使用if判断来为不同页面输入不同参数,如

$mid='';
$cid=0;
$size=5;
if ($this->is('post')){
$cid=$this->cid;
$mid=$this->categories[0]['mid'];
$size=5;
}
隐私评论
  1. 小魏先生
    小魏先生

    如何单独页面输出相关分类下的文章

    2022年11月22日
    1. 泽泽社长
      泽泽社长
      @小魏先生

      独立页面模板+输出分类文章(http://t.160.me/11.html)

      2022年11月22日
      1. 小魏先生
        小魏先生
        @泽泽社长

        我的意思是从一篇文章下点击相关文章跳转到单独的页面然后输出改文章的相关文章,感觉好像有点麻烦狗头

        2022年11月25日
        1. 泽泽社长
          泽泽社长
          @小魏先生

          我的回答依旧是那样,比如点击相关文章后页面跳转到相关文章的独立页面同时传递文章cid参数,然后相关文章页面根据cid输出相关文章

          2022年11月25日
  2. 加满都
    加满都

    随机文章这个,需要显示一张缩略图改怎么做呢

    2022年11月19日
    1. 泽泽社长
      泽泽社长
      @加满都

      正常使用你的缩略图函数就行,函数中的$this改成$to

      2022年11月20日
  3. Sirit
    Sirit

    不错不错,学到了。

    2022年11月12日
辽ICP备2022004655号