Как создать шаблон страницы из плагина, чтобы появился выбор в атрибутах страницы
Дополнение к третьему способу для статьи 3 способа создать шаблон страницы
1 Вариант: с единственным шаблоном
add_filter( 'theme_page_templates', 'my_plugin_template' );
add_filter( 'template_include', 'my_plugin_template_to_page' );
function my_plugin_template( $templates ) {
// выбор шаблона в атрибутах
$templates['full-page.php'] = 'Full Page';
return $templates;
}
function my_plugin_template_to_page( $template ) {
// запрашиваем активный шаблон текущей страницы
$page_template = get_page_template_slug();
// сравнение активного шаблона и шаблона выбранного в атрибутах
if ( 'full-page.php' == basename( $page_template ) ) {
// подключение шаблона, если выбран 'Full Page'
return wp_normalize_path( WP_PLUGIN_DIR . '/mland/templates/full-page.php' );
}
return $template;
}
2 Вариант: с несколькими шаблонами в одной папке плагина
Имя шаблона в атрибутах автоматически становится вида: My Template.
add_filter( 'theme_page_templates', 'my_plugin_template' );
add_filter( 'template_include', 'my_plugin_template_to_page' );
## выбор шаблонов из плагина в атрибутах страницы
function my_plugin_template( $templates ) {
## сканируем папку шаблонов в плагине
// define( 'ML_TEMPLATES_DIR', WP_PLUGIN_DIR . '/my-plugin/templates' );
$array_templates = array_diff( scandir( ML_TEMPLATES_DIR ), array('.', '..') );
foreach( $array_templates as $plugin_template ) {
$str_template = str_replace( ".php", "", $plugin_template ); // очищаем от .php
$str_template = str_replace( "-", " ", $str_template ); // очищаем от "-"
// Выводим имя в формате: My Template
$template_name = mb_convert_case( $str_template, MB_CASE_TITLE, 'UTF-8' );
// Подключаем выбор шаблона в атрибутах
$templates[ $plugin_template ] = $template_name;
}
return $templates;
}
## подключение шаблонов из плагина
function my_plugin_template_to_page( $template ) {
// запрашиваем активный шаблон текущей страницы
$page_template = get_page_template_slug();
## подключение шаблонов
// сканируем папку с шаблонами
$mland_templates = array_diff( scandir( ML_TEMPLATES_DIR ), array('.', '..') );
foreach( $mland_templates as $mland_template ) {
// сравнение активного шаблона и шаблона выбранного в атрибутах
if ( $mland_template == basename ( $page_template ) ) {
// подключение шаблона
return wp_normalize_path( ML_TEMPLATES_DIR . '/' . $mland_template );
}
}
return $template;
}
--
Заметка создана из комментария.