更新日期:2023-03-09

get_template_part 這個函數有 template 字樣,顧名思義就是關於佈景。一般來說,文章使用 single.php 檔案,這程式構造就是引入 get_header()、get_sidebar()、get_sidebar(),然後顯示文章內容就是寫程式讀進來。這樣子做所有文章長相都一模一樣,如果說我們寫了一篇文章是要展示照片、讓他有特效,這時候 get_template_part() 就可以派上用場了,因為他可以呼叫另一個版型來用。

函數用法:

get_template_part( $slug, $name );

變數說明:

$slug (必須) 通用的模版名稱。
$name (非必須) 指定的模版名稱。

範例:

get_template_part( 'content' , 'movie' );

就上面的程式來說,他會依照下面的順序找版型檔案,

  1. wp-content/themes/my_template_child/content-movie.php
  2. wp-content/themes/my_template_child/content.php
  3. wp-content/themes/my_template/content-movie.php
  4. wp-content/themes/my_template/content.php

若有子版型會先找找看有無符合,然後將 ‘content’ 和 ‘movie’ 組合起來,找 content-movie.php 檔案,沒有的話變成找 content.php

官方說明:

http://codex.wordpress.org/Function_Reference/get_template_part