在Typecho主題開發的過程中,置頂功能是一項很實用的功能,這次在重寫主題時,看到別人有的置頂文章這種功能,于是自己參考 Sticky插件 寫了這種方法,添加在自己主題里
在Typecho主題開發的過程中,置頂功能是一項很實用的功能,這次在重寫主題時,看到別人有的置頂文章這種功能,于是自己參考 Sticky插件 寫了這種方法,添加在自己主題里。頁希望能幫助到各位T主題開發者。
- 原文參考:詳情
跟 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(null,"(case cid$order end)"); //置頂文章的順序 按 $sticky 中 文章ID順序
if ($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)); //置頂文章不計算在所有文章內
}