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

深度解析 WordPress 模板加載核心:get_template_part() 函數全攻略

     編輯:PHP 綜合知識

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' ):

  1. wp-content/themes/twentytenchild/loop-index.php
  2. wp-content/themes/twentytenchild/loop.php
  3. wp-content/themes/twentyten/loop-index.php
  4. wp-content/themes/twentyten/loop.php

這機制完美支援子主題覆蓋父主題模板片段,無需複製整個文件。

實戰場景

1. 文章循環中按格式載入不同模板

<?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。

2. 導航欄多變體復用

<?php get_template_part( 'nav' );        // nav.php
get_template_part( 'nav', '2' );      // nav-2.php
get_template_part( 'nav', 'single' ); // nav-single.php ?>

進階:Hook 機制 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 );

源碼級剖析(WP 核心)

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 主題開發的基石技能。

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