typecho主题开发中常用的函数(更新版)

typecho主题开发中常用的函数(更新版)

小唐
2023-05-15 / 0 评论 / 126 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2023年05月15日,已超过346天没有更新,若内容或图片失效,请留言反馈。

本文收集一些在typecho主题开发中常用的函数,并不断更新。

typecho输出文章缩略图
/** 输出文章缩略图 */
function showThumbnail($widget)
{
    // 当文章无图片时的默认缩略图
    $rand = rand(1,5); // 随机 1-5 张缩略图
    $random = $widget->widget('Widget_Options')->themeUrl . '/img/' . $rand . '.jpg'; 
   // 随机缩略图路径
   // $random = $widget->widget('Widget_Options')->themeUrl . '/img/mr.jpg'; 
   // 若只想要一张默认缩略图请删除本行开头的"//"

    $attach = $widget->attachments(1)->attachment;
    $pattern = '/\<img.*?src\=\"(.*?)\"[^>]*>/i';


if (preg_match_all($pattern, $widget->content, $thumbUrl)) {
         echo $thumbUrl[1][0];
    } else     if ($attach->isImage) {
      echo $attach->url;
    } else {
        echo $random;
    }
}

调用方法

<?php showThumbnail($this); ?>
typecho输出随机文章
class Widget_Contents_Post_Rand extends Widget_Abstract_Contents
{
public function execute()
{
$this->parameter->setDefault(array('pageSize' => $this->options->postsListSize));
$this->db->fetchAll($this->select()
->where('table.contents.status = ?', 'publish')
->where('table.contents.created options->time)
->where('table.contents.type = ?', 'post')
->order('RAND()', Typecho_Db::SORT_DESC)
->limit($this->parameter->pageSize), array($this, 'push'));
}
}

调用方法

<?php $this->widget('Widget_Contents_Post_Rand','pageSize=10')->to($Rand);while($Rand->next()): ?>
Title增加副标题
<?php if ($this->is('index')): ?> - 副标题<?php endif; ?>
分页标题
<title><?php if($this->_currentPage>1) echo '第 '.$this->_currentPage.' 页 - '; ?><?php $this->archiveTitle(' » ', '', ' - '); ?><?php $this->options->title(); ?></title>
typecho输出相关文章
<?php $this->related(5)->to($relatedPosts); ?>
    <ul>
    <?php while ($relatedPosts->next()): ?>
    <li><a href="<?php $relatedPosts->permalink(); ?>" title="<?php $relatedPosts->title(); ?>"><?php $relatedPosts->title(); ?></a></li>
    <?php endwhile; ?>
</ul>
文章阅读量统计

在 模板文件func­tions.php 中加入下面代码

function get_post_view($archive)
{
    $cid    = $archive->cid;
    $db     = Typecho_Db::get();
    $prefix = $db->getPrefix();
    if (!array_key_exists('views', $db->fetchRow($db->select()->from('table.contents')))) {
        $db->query('ALTER TABLE `' . $prefix . 'contents` ADD `views` INT(10) DEFAULT 0;');
        echo 0;
        return;
    }
    $row = $db->fetchRow($db->select('views')->from('table.contents')->where('cid = ?', $cid));
    if ($archive->is('single')) {
       $db->query($db->update('table.contents')->rows(array('views' => (int) $row['views'] + 1))->where('cid = ?', $cid));
    }
    echo $row['views'];
}

调用方法

<?php get_post_view($this) ?>
0

评论

博主关闭了所有页面的评论,留言评论可通过微信关注公众号:得水小筑