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

深入解析 WordPress 核心函數 post_class 與 get_post_class

     編輯:PHP 綜合知識

在 WordPress 主題開發中,post_class() 與 get_post_class() 是兩個不可或缺的核心函數,它們能為每篇文章自動生成唯一且語義豐富的 CSS 類別。善用這兩個函數,配合靈活的 CSS 樣式,輕鬆打造出極具個性化的部落格佈局。

post_class():直接輸出文章類別屬性

函數說明

post_class() 會直接在 HTML 標籤中出 class="..." 屬性,包含文章 ID、類型、狀態、格式、分類、標籤等資訊。它不返回任何值,僅負責輸出,類似 the_title() 這類不帶 get_ 前綴的模板標籤。

基本用法

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
    <?php the_content(); ?>
</article>

注意:呼叫時不需寫成 class="<?php post_class(); ?>",函數已內建輸出完整的 class="..." 字串。

實際輸出範例

<article id="post-888" class="post-888 post type-post status-publish format-standard hentry category-2 tag-wordpress">
    文章內容
</article>

原始碼解析

function post_class( $class = '', $post_id = null ) {
    // 以單一空格分隔類別,彙整給 post DIV 使用
    echo 'class="' . join( ' ', get_post_class( $class, $post_id ) ) . '"';
}

可見 post_class() 實際上是 get_post_class() 的簡易封裝,負責將陣列轉為字串並輸出。

get_post_class():取得文章類別陣列,靈活客製化

函數特性

get_post_class() 回傳一個包含文章所有相關類別的陣列,支援傳入自訂類別(字串或陣列)合併進結果中。這讓開發者能在需要精細控制輸出時(如判斷條件式輸出、加上特定前綴等)靈活運用。

函數簽名

get_post_class( $class = '', $post_id = null );
  • $class:自訂類別,字串或陣列皆可
  • $post_id:指定文章 ID,預設為迴圈內當前文章

基本範例

$classes = get_post_class();
var_dump($classes);

輸出結果

array(9) {
  [0]=> string(8) "post-249"
  [1]=> string(4) "post"
  [2]=> string(9) "type-post"
  [3]=> string(14) "status-publish"
  [4]=> string(15) "format-standard"
  [5]=> string(6) "hentry"
  [6]=> string(18) "category-catcatcat"
  [7]=> string(8) "tag-tag1"
  [8]=> string(8) "tag-tag2"
}

進階用法:加入自訂類別

// 字串方式
$classes = get_post_class( 'index-post', 249 );

// 陣列方式
$classes = get_post_class( array( 'index-post', 'featured' ), 249 );
var_dump($classes);

輸出結果

array(10) {
  [0]=> string(8) "post-249"
  [1]=> string(4) "post"
  [2]=> string(9) "type-post"
  [3]=> string(14) "status-publish"
  [4]=> string(15) "format-standard"
  [5]=> string(6) "hentry"
  [6]=> string(18) "category-catcatcat"
  [7]=> string(8) "tag-tag1"
  [8]=> string(8) "tag-tag2"
  [9]=> string(10) "index-post"
}

類別生成順序與語義總結

依據原始碼邏輯,get_post_class() 產生的類別順序如下:

  1. 文章唯一 ID:post-{ID}
  2. 文章類型基礎類別:post、page 等
  3. 文章類型前綴類別:type-post、type-page
  4. 發布狀態:status-publish、status-draft 等
  5. 文章格式:format-standard、format-video 等
  6. 密碼保護標記:post-password-required(如有設置)
  7. 所屬分類:每個分類產生 category-{slug}
  8. 所屬標籤:每個標籤產生 tag-{slug}
  9. 自訂類別:開發者傳入的額外類別

實戰建議

  • 主題開發時,務必在文章容器標籤(<article>、<div>)上呼叫 post_class(),確保樣式系統完整運作
  • 需要條件式輸出或加上 BEM 命名規範時,改用 get_post_class() 取得陣列後自行處理
  • 善用自訂類別參數,為特定版面(如首頁列表、側邊欄推薦)加上專用類別,避免 CSS 衝突

掌握這兩個函數,能讓你的 WordPress 主題結構更語義化、樣式更好維護,是主題開發者的必修課。

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