問題描述
有沒有辦法在模板開始時自動運行 get_header(),最後是 get_footer()?
目前我的代碼與這些調用太重複了。
我一直在尋找一種方法來做到這一點,但是我在 Google 中找不到。
最佳解決方案
看看 wp-includes/template-loader.php … 似乎有一種方法:
if ( $template = apply_filters( 'template_include', $template ) )
include( $template );
您可以掛接該過濾器,處理回調函數中的包含並返回 FALSE 。
示例代碼,未測試:
add_filter( 'template_include', function( $template ) {
get_header();
include $template;
get_footer();
return FALSE;
});
次佳解決方案
@scribu 提出了一種減少 WordPress 模板中的代碼重複的方法,他稱之為 theme wrappers,它實現了您正在尋找的內容。 roots theme 使用輕微修改的 version of this method 。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。