WordPress 3.0 引入 get_template_part() 後,主題開發邁入「模組化」新時代。它不同於 get_header()、get_footer() 等固定區塊函數,提供極具彈性的模板片段復用機制,並內建子主題覆蓋優先級與 fallback 機制。本文從參數、載入優先級、實戰場景到內部 Hook 機制全方位剖析。
<?php get_template_part( $slug, $name ); ?>
$slug(必填):通用模板標識,如 content、loop、nav$name(可選):專用模板標識,如 single、page、index最終嘗試載入的文件名為 {slug}-{name}.php,若不存在則 fallback 到 {slug}.php。
假設父主題 twentyten,子主題 twentytenchild,調用 get_template_part( 'loop', 'index' ):
wp-content/themes/twentytenchild/loop-index.phpwp-content/themes/twentytenchild/loop.phpwp-content/themes/twentyten/loop-index.phpwp-content/themes/twentyten/loop.php這機制完美支援子主題覆蓋父主題模板片段,無需複製整個文件。
<?php while ( have_posts() ) : the_post();
get_template_part( 'content', get_post_format() );
endwhile; ?>
標準格式載入 content.php,圖片格式載入 content-image.php,視頻格式載入 content-video.php,若對應文件不存在自動 fallback 到 content.php。
<?php get_template_part( 'nav' ); // nav.php
get_template_part( 'nav', '2' ); // nav-2.php
get_template_part( 'nav', 'single' ); // nav-single.php ?>
get_template_part_{$slug}函數內部執行 do_action( "get_template_part_{$slug}", $slug, $name ),Hook 名稱動態包含 $slug。這意味著:
get_template_part_content 可在每次載入 content-* 模板前執行邏輯get_template_part_nav 可注入導航相關資源示例:在載入 content-* 前自動註入閱讀量統計
add_action( 'get_template_part_content', function( $slug, $name ) {
if ( is_singular() ) {
// 更新文章瀏覽數等邏輯
}
}, 10, 2 );
function get_template_part( $slug, $name = null ) {
do_action( "get_template_part_{$slug}", $slug, $name );
$templates = array();
if ( isset( $name ) )
$templates[] = "{$slug}-{$name}.php";
$templates[] = "{$slug}.php";
locate_template( $templates, true, false );
}
locate_template() 會按優先級查找並 load_template() 載入,第三參數 false 表示不要求文件必須存在(找不到不報錯)。
善用 get_template_part(),能讓主題結構清晰、易維護、極易擴展,是專業 WordPress 主題開發的基石技能。