首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

WordPress 開發必備:get_category() 獲取分類詳情、get_children() 獲取子頁面/附件完全指南

     編輯:PHP 綜合知識

主題開發中頻繁需要「獲取指定分類對象」與「獲取文章附件/子頁面」。WordPress 提供 get_category() 和 get_children() 兩個核心函數,本文系統整理參數、返回結構、實戰場景與避坑指南。

get_category( $category, $output, $filter )

參數

參數類型說明
$categoryint|object分類 ID 或分類對象
$outputstring返回類型:OBJECT(默認) / ARRAY_A / ARRAY_N
$filterstring過濾模式:raw / edit / display (默認 display)

返回對象結構 (OBJECT 模式)

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_parentint0父文章/頁面 ID,0 表示任意
post_typestring'any'attachment/page/revision/any
post_mime_typestring''MIME 類型過濾,如 image、image/jpeg
numberpostsint-1獲取數量,-1 無限制
post_statusstring'any'publish/draft/inherit/any
orderby/orderstring'menu_order ASC'排序字段/方向

實戰 1:獲取文章第一張圖片作為縮略圖(兼容無特色圖像)

$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');
}

實戰 2:獲取頁面的所有子頁面(導航菜單構建)

$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_parent
  • 附件的 post_status 為 inherit,查詢附件時務必設置 'post_status'=>'inherit' 或 'any'
  • 返回類型 $output 同 get_posts():OBJECT/ARRAY_A/ARRAY_N
  • 性能:大量附件時,考慮用 WP_Query + fields=>ids 只取 ID,再批量 wp_get_attachment_image_src()

掌握這兩個函數,即可在主題中優雅處理「分類詳情展示」與「附件/子頁面聚合」兩大高頻需求,無需寫原生 SQL。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved