在 WordPress 裡我們可以透過 get_the_category() 取得文章的分類,丟 post_id 進去,或是透過 get_post() 取得文章內容後就可以拿到分類的資料。
get_the_category( int $post_id = false )
例如:
the_post(); $categories = get_the_category();
var_dump($categories) 可以得到類似以下的內容:
array(1) {[0]=> object(stdClass)#310 (17) { ["term_id"]=> &int(6) ["name"]=> &string(10) "familylife" ["slug"]=> &string(10) "familylife" ["term_group"]=> int(0) ["term_taxonomy_id"]=> int(6) ["taxonomy"]=> string(8) "category" ["description"]=> &string(0) "" ["parent"]=> &int(0) ["count"]=> &int(208) ["object_id"]=> int(7729) ["filter"]=> string(3) "raw" ["cat_ID"]=> &int(6) ["category_count"]=> &int(208) ["category_description"]=> &string(0) "" ["cat_name"]=> &string(10) "familylife" ["category_nicename"]=> &string(10) "familylife" ["category_parent"]=> &int(0) }}也因為一篇文章可以屬於很多個分類,所以要取得分類的名字時,要指定是第幾個。
echo $categories[0]->name;
要取得分類的網址則是使用 get_category_link(),我們把取得的 id 丟進去:
$category_link = get_category_link( $categories[0]->term_id );