菜鸟站长
个人博客主题模板、应用插件、功能开发技术资源聚合分享网站

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

发布者:菜鸟站长  发布日期:2023-12-27  更新日期:2023-12-27  人气指数:130

两步实现 Typecho 随机文章 与同分类下 随机文章

后台 功能代码

在主题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; ?>
本文检索关键词:typecho教程 , 随机文章

菜鸟站长推荐教程



添加新评论 »

icon_mrgreen.pngicon_neutral.pngicon_twisted.pngicon_arrow.pngicon_eek.pngicon_smile.pngicon_confused.pngicon_cool.pngicon_evil.pngicon_biggrin.pngicon_idea.pngicon_redface.pngicon_razz.pngicon_rolleyes.pngicon_wink.pngicon_cry.pngicon_surprised.pngicon_lol.pngicon_mad.pngicon_sad.pngicon_exclaim.pngicon_question.png