get_the_category()

get_the_category()函数返回的值是一个数组形式的对象,用来返回当前文章所属的类别的若干属性,该数组包括以下内容:

cat_ID:当前类别的ID(也可以写作’term_id’);
cat_name:当前类别的名称(也被写作’name’);
category_description:当前分类的描述(也可以写作’description’);
category_count:属于当前分类的文章数量(也被写作’count’)。
category_nicename:别名,存储在slug字段
category_parent:父类别编号,没有父类的为0,存储在parent字段

具体的使用方法,我们通过下面的几个句子来说明:

显示第一个类别的名称:

<?php
$category = get_the_category();
echo $category[0]->cat_name;
?>

显示多个分类名称(当一个篇文章有多个分类的时候):

<?php
$cat = get_the_category();
foreach($cat as $key=>$category)
{
echo $category->cat_name.'<br/>';
}
?>

显示分类的所有内容:

<?php $categories = get_the_category(); var_dump($categories);?>

通过get_the_category()函数我们就可以在文章的循环外获取分类的内容,这样我们就可以用在很多的功能中,比如可以在每篇文章下面添加一个相关文章列表。

官网:https://developer.wordpress.org/reference/functions/get_the_category/