在開發(fā)wordpress主題時,在主題里添加自定義頁面模板很簡單,那么,怎么用插件來添加自定義頁面模板呢?我在開發(fā)插件時有這個需求,通過互聯(lián)網(wǎng)知道了一點有用的信息,這一次的wordpress開發(fā)教程就分享下通過插件添加自定義頁面模板這個方法。
自定義頁面模板:
我們在主題根目錄下新建文件夾:page,在page文件夾中添加文件page-test.php
文件,填入以下內(nèi)容:
<?php
/* template name: Test頁面 */
get_header();
?>
恭喜你,成功了
<?php get_footer();
核心:
我們在插件中添加以下代碼,讓插件加載模板文件并調(diào)用
//添加頁面模板
//從特定頁加載模板
add_filter( 'page_template', 'wpa3396_page_template' );
function wpa3396_page_template( $page_template ){
if ( get_page_template_slug() == 'page-test.php' ) {
$page_template = dirname( __FILE__ ) . '/page/page-test.php';
}
return $page_template;
}
/**
* 將“自定義”模板添加到頁面屬性模板部分。
*/
add_filter( 'theme_page_templates', 'wpse_288589_add_template_to_select', 10, 4 );
function wpse_288589_add_template_to_select( $post_templates, $wp_theme, $post, $post_type ) {
// 添加自定義模板到頁面選擇下拉列表
$post_templates['page-test.php'] = __('Test頁面');
return $post_templates;
}
效果驗證:
轉(zhuǎn)到后臺新建頁面,選擇Test頁面模板即可看到效果。
如果是從主題中新建自定義頁面模板,那就更簡單了,大家可參考這篇wordpress開發(fā)教程: