問題描述
是否可以使用插件提供自定義頁面模板?
最佳解決方案
get_page_template()可以通過 page_template 濾波器覆蓋。如果您的插件是一個目錄,其中包含模板作為文件,那只是傳遞這些文件的名稱的問題。如果要 「快速創建」(在管理區域中編輯它們並將其保存在數據庫中),您可能需要將它們寫入緩存目錄並引用它們,或者掛接到 template_redirect 並執行一些瘋狂 eval()的東西。
一個插件的一個簡單的例子,如果某個標準是真的,”redirects” 到同一個插件目錄中的一個文件:
add_filter( 'page_template', 'wpa3396_page_template' );
function wpa3396_page_template( $page_template )
{
if ( is_page( 'my-custom-page-slug' ) ) {
$page_template = dirname( __FILE__ ) . '/custom-page-template.php';
}
return $page_template;
}
次佳解決方案
覆蓋 get_page_template()只是一個快速的黑客。它不允許從管理屏幕中選擇模板,並且頁面插件是 hard-coded 插入插件,因此用户無法知道模板來自哪裏。
首選解決方案是遵循 this tutorial,它允許您從 plug-in 在 back-end 中註冊頁面模板。然後它就像任何其他模板一樣工作。
/*
* Initializes the plugin by setting filters and administration functions.
*/
private function __construct() {
$this->templates = array();
// Add a filter to the attributes metabox to inject template into the cache.
add_filter('page_attributes_dropdown_pages_args',
array( $this, 'register_project_templates' )
);
// Add a filter to the save post to inject out template into the page cache
add_filter('wp_insert_post_data',
array( $this, 'register_project_templates' )
);
// Add a filter to the template include to determine if the page has our
// template assigned and return it's path
add_filter('template_include',
array( $this, 'view_project_template')
);
// Add your templates to this array.
$this->templates = array(
'goodtobebad-template.php' => 'It's Good to Be Bad',
);
}
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。