問題描述
我正在研究一個小孩主題,我強烈不想覆蓋主模板檔案,以保持子主題的簡單性,並儘量減少程式碼量和維護時間。
在迴圈中,父主題中的 index.php 模板使用:get_template_part( 'content' );
這將帶來 content.php,我希望它的行為更像 get_template_part( 'content', get_post_format() ); 或類似的,以便引入不同的模板,如 content-aside.php 等,而不是在子主題中建立一個 index.php 來覆蓋父進行單線更改。
get_template_part()包括:
function get_template_part( $slug, $name = null ) {
do_action( "get_template_part_{$slug}", $slug, $name );
$templates = array();
$name = (string) $name;
if ( '' !== $name )
$templates[] = "{$slug}-{$name}.php";
$templates[] = "{$slug}.php";
locate_template($templates, true, false);
}
所以有一個動作可用,在我的情況下叫做 get_template_part_content
我可以鉤到具有類似的作用:
add_action( 'get_template_part_content', 'child_post_styles', 10, 2 );
function child_post_styles ( $slug, $name ) {
if( false == $name ){
$name = get_post_format();
$templates = array();
if ( '' !== $name )
$templates[] = "{$slug}-{$name}.php";
$templates[] = "{$slug}.php";
locate_template($templates, true, false);
}
}
這顯然導致了重複的重複,一個來自我的掛鉤功能,可以顯示所需的模板,另一個來自 get_template_part()中的正常 locate_template 呼叫
我無法找到一種方式來完成這個沒有重複,或者沒有結束頁面渲染後,透過做一些愚蠢的服務我的模板部分,如 break 或 exit
最佳解決方案
沒有鉤子這樣做。將 index.php 複製到子主題,並使單行更改。另外,告訴家長主題的作者,他們應該在主題中做出相同的改變,以實現靈活性。
次佳解決方案
我認為這是不可能實現的方式。真的很煩,沒有得到一個過濾器來改變模板檔名稱:(
我有一個解決辦法。讓 content.php 進行比較。
// content.php file
$format = get_post_format();
if( '' != $format ){
get_template_part( 'content-'. $format );
}
else{
get_template_part( 'content-default' );
}
我沒有使用 get_template_part 函式的第二個引數,而是在第一個引數上傳遞了字尾,以避免在 content.php 檔案上有不定式的呼叫,如果沒有'content-'. $format 檔案。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。