主題開發中頻繁需要「獲取指定分類對象」與「獲取文章附件/子頁面」。WordPress 提供 get_category() 和 get_children() 兩個核心函數,本文系統整理參數、返回結構、實戰場景與避坑指南。
get_category( $category, $output, $filter )| 參數 | 類型 | 說明 |
|---|---|---|
$category | int|object | 分類 ID 或分類對象 |
$output | string | 返回類型:OBJECT(默認) / ARRAY_A / ARRAY_N |
$filter | string | 過濾模式:raw / edit / display (默認 display) |
stdClass Object (
[term_id] => 5 // 分類 ID (術語表主鍵)
[name] => 'Cat Name' // 分類名
[slug] => 'cat' // 別名
[term_group] => 0
[term_taxonomy_id] => 5 // 術語分類表 ID
[taxonomy] => 'category' // 分類法
[description] => '' // 描述
[parent] => 70 // 父分類 ID
[count] => 0 // 文章數
[cat_ID] => 5 // 別名字段
[category_count] => 0
[category_description] => ''
[cat_name] => 'Category Name'
[category_nicename] => 'category-name'
[category_parent] => 70
)
$cats = get_the_category(); // 文章分類陣列
if ($cats) {
$cat = get_category($cats[0]); // 獲取完整對象
$parent = $cat->parent ? get_category($cat->parent) : $cat;
echo '<a href="' . get_category_link($parent->term_id) . '">' . $parent->name . '</a>';
}
get_children( $args, $output )類似 get_posts() 但專門針對「父子關係」:附件、修訂版、子頁面。默認查詢 post_parent 為當前文章的所有子項。
$args 完整鍵名| 鍵名 | 類型 | 默認 | 說明 |
|---|---|---|---|
| post_parent | int | 0 | 父文章/頁面 ID,0 表示任意 |
| post_type | string | 'any' | attachment/page/revision/any |
| post_mime_type | string | '' | MIME 類型過濾,如 image、image/jpeg |
| numberposts | int | -1 | 獲取數量,-1 無限制 |
| post_status | string | 'any' | publish/draft/inherit/any |
| orderby/order | string | 'menu_order ASC' | 排序字段/方向 |
$args = array(
'post_parent' => $post->ID,
'post_type' => 'attachment',
'post_mime_type' => 'image',
'numberposts' => 1,
'order' => 'ASC',
);
$images = get_children($args);
if ($images) {
$img = array_shift($images);
echo wp_get_attachment_image($img->ID, 'thumbnail');
}
$subpages = get_children(array(
'post_parent' => $post->ID,
'post_type' => 'page',
'numberposts' => -1,
'orderby' => 'menu_order',
'order' => 'ASC',
));
foreach ($subpages as $page) {
echo '<li><a href="' . get_permalink($page->ID) . '">' . $page->post_title . '</a></li>';
}
get_children() **不支援** meta_query / tax_query,複雜條件請用 get_posts() + post_parentpost_status 為 inherit,查詢附件時務必設置 'post_status'=>'inherit' 或 'any'$output 同 get_posts():OBJECT/ARRAY_A/ARRAY_NWP_Query + fields=>ids 只取 ID,再批量 wp_get_attachment_image_src()掌握這兩個函數,即可在主題中優雅處理「分類詳情展示」與「附件/子頁面聚合」兩大高頻需求,無需寫原生 SQL。