这次在重写主题时,看到别人有的置顶文章这种功能,于是自己参考 Sticky插件 写了这种方法,添加在自己主题里~

跟 Sticky插件 一样

在 index.php 的 $this->title(); 前面加上 $this->sticky();可出现这段 html. 
例: <h2 class="title"><a href="<?php $this->permalink() ?>"><?php $this->sticky(); $this->title() ?></a></h2>

代码放在主题下index.php中:

/** 文章置顶 */
$sticky = '1'; //置顶的文章id,多个用|隔开
if($sticky){
    $sticky_cids = explode('|',$sticky); //分割文本
    $sticky_html = "<span style='color:red'>[置顶] </span>"; //置顶标题的 html

    $db = Typecho_Db::get();
    $pageSize = $this->options->pageSize;
    $select1 = $this->select()->where('type = ?', 'post');
    $select2 = $this->select()->where('type = ? && status = ? && created < ?', 'post','publish',time());

    //清空原有文章的列队
    $this->row = [];
    $this->stack = [];
    $this->length = 0;

    $order = '';
    foreach($sticky_cids as $i => $cid) {
        if($i == 0) $select1->where('cid = ?', $cid);
        else $select1->orWhere('cid = ?', $cid);
        $order .= " when $cid then $i";
        $select2->where('table.contents.cid != ?', $cid); //避免重复
    }
    if ($order) $select1->order('', "(case cid$order end)"); //置顶文章的顺序 按 $sticky 中 文章ID顺序
    if (($this->_currentPage || $this->currentPage) == 1) foreach($db->fetchAll($select1) as $sticky_post){ //首页第一页才显示
        $sticky_post['sticky'] = $sticky_html;
        $this->push($sticky_post); //压入列队
    }

    $uid = $this->user->uid; //登录时,显示用户各自的私密文章
    if($uid) $select2->orWhere('authorId = ? && status = ?',$uid,'private');

    $sticky_posts = $db->fetchAll($select2->order('table.contents.created', Typecho_Db::SORT_DESC)->page($this->_currentPage, $this->parameter->pageSize));
    foreach($sticky_posts as $sticky_post) $this->push($sticky_post); //压入列队
    $this->setTotal($this->getTotal()-count($sticky_cids)); //置顶文章不计算在所有文章内
}

更新

2021.10.14

  • 适配 1.2

2018.2.6

  • 登录时,显示用户各自的私密文章

2018.2.7

  • 隐藏定时发送的文章

2018.2.27

  • 解决重复显示的问题

支付宝红包

支付宝

微信

标签: php, typecho

已有 16 条评论

  1. True True 访客 Chrome Windows 10 回复

    后台设置显示8篇文章,使用置顶就变9个,导致首页变形。怎么解决呢?

    1. 小さな手は 小さな手は 博主 Chrome Android 7.0 回复

      回复 @True

      看具体情况

  2. True True 访客 Chrome Windows 10 回复

    逛博中。。。。

  3. Jrotty Jrotty 访客 Chrome Windows 10 回复

    666哇

    1. Jrotty Jrotty 访客 Chrome Windows 10 回复

      回复 @Jrotty

      转走啦,233,顺便加了个判断,只在首页有效

      1. 泽泽 泽泽 访客 Chrome Android 8.1.0 回复

        回复 @Jrotty

        测试回复

  4. 品牌设计 品牌设计 访客 Chrome Windows 7 回复

    喜欢滑动页面

添加新评论

注意:已开启评论过滤器,无中文无法评论!
泡泡表情