Typecho 的 $this 里到底有什么 之 详情页相关

常用代码片段

前前后后也写过几十个 Typecho 主题了,很多时候写到一半还是会去搜索 “Typecho 常用代码片段” 来做参考。但是,对于一些特殊的页面判断逻辑,搜索往往找不到想要的内容,这个时候,明白 Typecho 的 $this 里到底有什么,就非常有帮助了

打印出 $this,挑重点看一下(输出内容太多,不一一展开了)

$this->title //文章标题
$this->permalink //文章链接
$this->slug // 文章 Slug
$this->cid // 文章 cid
$this->created // 创建时间,时间戳形式
$this->modified // 最后修改时间,时间戳形式
$this->status // 文章状态,例如 “publish”
$this->authorId // 文章作者的 ID
$this->categories // 文章所属分类,下文详解
$this->directory // 同样是文章所属的分类,下文详解
$this->category // 文章所属的最近的分类 slug
$this->commentsNum // 文章评论数量
$this->allowComment // 是否允许评论,0 或 1
$this->feedUrl
$this->feedRssUrl
$this->feedAtomUrl

三种输出分类的方式有什么区别 ?

以文章:https://paoti.club/archives/typecho-code-explanation-is.html 为例子

这篇文章的一些基础信息如下

  • 归属于分类 Typecho
  • Typecho 是一个子分类,它的名称是 Typecho,它的 slug 为 typecho,它的 mid 为 6
  • Typecho 的父分类名称是网站&服务器,slug 是 websites,mid 是 1

分别看一下三种分类的输出

$this->category

$this->category 的输出是 'typecho',也就是最近层级分类的 slug

$this->categories

$this->categories 的输出如下,输出了最近层级子分类的全部信息

array ( 
    0 => array ( 
        'mid' => '6', // 分类的 mid
        'name' => 'Typecho', // 分类名称
        'slug' => 'typecho', // 分类 Slug
        'type' => 'category', 
        'description' => NULL, // 分类描述
        'count' => '2', // 分类下文章的数量
        'order' => '1', // 分类排序
        'parent' => '1', // 父分类的 mid
        'cid' => '49', // 当前文章的 cid
        'directory' => array ( // 所有分类,包括子分类和父分类的 slug 数组
            0 => 'websites',
            1 => 'typecho',
        ),
        'permalink' => 'https://paoti.club/category/typecho/', 
        'feedUrl' => 'https://paoti.club/feed/category/typecho/',
        'feedRssUrl' => 'https://paoti.club/feed/rss/category/typecho/',
        'feedAtomUrl' => 'https://paoti.club/feed/atom/category/typecho/', 
    ), 
)

$this->directory

$this->directory 的输出如下,是所有子分类和父分类的 Slug 数组

array ( 
    0 => 'websites',
    1 => 'typecho',
)

用法示例

获取文章最近一个分类的 mid

$this->categories[0]['mid']

当前文章是否归于某个分类 “something”

<?php if(in_array("something",$this->directory)) ?>