WordPress分类函数:get_the_category()详解

作者: 小月雨田 分类: WordPress技巧 发布时间: 2020-03-02 11:49

  函数:get_the_category()

  说明:获取与查询参数相匹配的类别对象。

  文件位置在:wp-includes/category-template.php。函数用来返回的值是一个数组形式的对象,返回的内容是文章下分类信息,可以在文章主循环外使用(Loop)。

  用法:

<?php get_the_category( $id ) ?>

  参数说明:id:文章编号,类型为整数,该参数为可选项。默认值为$post->ID,当前文章编号。

  返回对象的成员:
  cat_ID:类别编号;存储在term_id字段;
  cat_name:类别名称,存储在name字段;
  category_nicename:别名,存储在slug字段;
  category_description:类别描述,存储在description字段;
  category_parent:父类别编号,没有父类的为0,存储在parent字段;
  category_count:类别使用的数量,存储在count字段;

  参考代码:

  1.显示类别的图片:

<?php foreach((get_the_category()) as category) { echo '<img src="http://example.com/images/' .category->cat_ID . '.jpg" alt="' . $category->cat_name . '" />'; } ?> 

  2.显示第一个类别名称:

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

  3.显示第一个类别的连接:

<?php category = get_the_category(); if(category[0]){ echo '<a href="'.get_category_link(category[0]->term_id ).'">'.category[0]->cat_name.'</a>'; } ?> 

  4.获取指定文章编号的类别信息:

<?php global post;categories = get_the_category(post->ID); var_dump(categories); ?> 

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

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

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!

一条评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注