WordPress 主題函數 get_the_category() 詳解使用

説明

獲取與查詢參數相匹配的類別對象

用法

  1. <?php get_the_category( $id ) ?>

參數

id

(整數) (可選) 文章編號

默認: $post->ID (當前文章的編號)

例子

顯示類別的圖片

  1. <?php
  2. foreach((get_the_category()) as $category) {
  3.     echo '<img src="http://www.2zzt.com/images/' . $category->cat_ID . '.jpg" alt="' . $category->cat_name . '" />';
  4. ?>

顯示第一個類別的名稱

  1. <?php
  2. $category = get_the_category();
  3. echo $category[0]->cat_name;
    1. <?php
    2. $category = get_the_category();
    3. if($category[0]){
    4. echo '<a href="'.get_category_link($category[0]->term_id ).'">'.$category[0]->cat_name.'</a>';
    5. }
      1. <?php
      2. global $post;
      3. $categories = get_the_category($post->ID);
      4. $categories);
      5. ?>

返回對象的成員

cat_ID

類別編號,存儲在 term_id 字段

cat_name

類別名稱,存儲在 name 字段

category_nicename

別名,存儲在 slug 字段

category_description

類別描述,存儲在 description 字段

category_parent

父類別編號,沒有父類的為 0,存儲在 parent 字段

category_count

類別使用的數量,存儲在 count 字段