Typecho 调用指定分类的第一篇文章

在主题的Function.php里添加一个方法:

/**  特色专科获取每个科室第一篇文章
by jaychen 20220506
 *
 *
 */
class tszkFirstPost extends Widget_Archive
{
    public function execute()
    {
        $select  = $this->select()->from('table.contents')->join('table.relationships','table.contents.cid=table.relationships.cid')
            ->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')
            ->where('table.relationships.mid = ?', $this->parameter->CategeId)
            ->limit(1)
            ->order('table.contents.cid', Typecho_Db::SORT_ASC);
        $this->db->fetchAll($select, array($this, 'push'));
    }
}

上面的代码是调用Widget_Archive方法并修改相关的查询条件,组成一个新的方法;

join是用来链接表的,用来筛选同分类下的文章;
第一、二行where是常规的筛选,排除加密文章和隐藏文章,这里由于我的项目中的这篇分类简介的文章是不需要显示到列表的,所以我们隐藏掉了,在方法中就需要注释掉,把隐藏的文章也放进结果里。大家可以视项目来调整;
下面的就是默认的条件了,筛选发布时间少于当前系统时间,筛选类型为文章;
最后一个where是用来筛选分类的,链接文章表和分类表后,由前端(使用$this->parameter->CategeId)传入当前页面的分类id,然后筛选只显示这个分类的文章结果;
limit是控制放回结果数量,1只要1条;
order是排序,按文章的cid大小来排序,倒叙排列,所以这个分类最早发布的文章就是第一行结果;

<?php $this->widget('tszkFirstPost@post','CategeId='.getCategeId($this->getArchiveSlug()))->to($post); ?>
        <div class="tszk_category_info">
            <?php while($post->next()): ?>
                <div class="pic"><img src="<?php showThumbnail($post); ?>" /></div>
                <div class="name"><?php $post->title()?>  科室简介</div>
                <div class="description"><?php $post->excerpt(128,'...');?></div>
                <a class="btn" href="<?php $post->permalink();?>">详细介绍</a>
                <div class="clearfix"></div>
            <?php endwhile; ?>
        </div>

前端代码我是用在Archive.php归档页面,也就是分类页面。

CategeId是给后端传入分类id的,可以按需要修改成其他
getCategeId($this->getArchiveSlug())是我写的一个方法,用来获取当前分类mid的,用来自动获取当前分类的mid,如果没这个需求直接改成想要的分类mid就可以。用同样需求的朋友可以增加下面的方法;
$this->getArchiveSlug()就是获取当前分类(支持子分类)的slug别名,再通过下面的方法查询到对应的分类mid。

/**
 * 获取当前栏目的mid
 *
 * @access public
 * @param string $default
 * @return void
 */
function getCategeId($slug)
{
    $db = Typecho_Db::get();
    $CategeId = $db->fetchRow($db->select()->from('table.metas')->where('slug=?', $slug)->where('type=?', 'category'));
    return $CategeId['mid'];
}
请登录后发表评论

    没有回复内容