在 WordPress 主題開發中,post_class() 與 get_post_class() 是兩個不可或缺的核心函數,它們能為每篇文章自動生成唯一且語義豐富的 CSS 類別。善用這兩個函數,配合靈活的 CSS 樣式,輕鬆打造出極具個性化的部落格佈局。
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( $class = '', $post_id = null );
$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() 產生的類別順序如下:
post-{ID}post、page 等type-post、type-pagestatus-publish、status-draft 等format-standard、format-video 等post-password-required(如有設置)category-{slug}tag-{slug}<article>、<div>)上呼叫 post_class(),確保樣式系統完整運作get_post_class() 取得陣列後自行處理掌握這兩個函數,能讓你的 WordPress 主題結構更語義化、樣式更好維護,是主題開發者的必修課。