How to create a page template from a plugin so that a selection appears in the page attributes
Additional to the third method for the article 3 ways to create a page template
1 Option: with a single template
add_filter( 'theme_page_templates', 'my_plugin_template' );
add_filter( 'template_include', 'my_plugin_template_to_page' );
function my_plugin_template( $templates ) {
// template selection in page attributes
$templates['full-page.php'] = 'Full Page';
return $templates;
}
function my_plugin_template_to_page( $template ) {
// request the active template of the current page
$page_template = get_page_template_slug();
// compare the active template and the template selected in the attributes
if ( 'full-page.php' == basename( $page_template ) ) {
// include the template if 'Full Page' is selected
return wp_normalize_path( WP_PLUGIN_DIR . '/mland/templates/full-page.php' );
}
return $template;
}
2 Option: with multiple templates in one plugin folder
The template name in the attributes automatically becomes in the format: My Template.
add_filter( 'theme_page_templates', 'my_plugin_template' );
add_filter( 'template_include', 'my_plugin_template_to_page' );
## select templates from the plugin in page attributes
function my_plugin_template( $templates ) {
## scan the template folder in the plugin
// 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 ); // clear of .php
$str_template = str_replace( "-", " ", $str_template ); // clear of "-"
// Output the name in the format: My Template
$template_name = mb_convert_case( $str_template, MB_CASE_TITLE, 'UTF-8' );
// Connect the template selection in the attributes
$templates[ $plugin_template ] = $template_name;
}
return $templates;
}
## connecting templates from the plugin
function my_plugin_template_to_page( $template ) {
// request the active template of the current page
$page_template = get_page_template_slug();
## connecting templates
// scan the template folder
$mland_templates = array_diff( scandir( ML_TEMPLATES_DIR ), array('.', '..') );
foreach( $mland_templates as $mland_template ) {
// compare the active template and the template selected in the attributes
if ( $mland_template == basename ( $page_template ) ) {
// connect the template
return wp_normalize_path( ML_TEMPLATES_DIR . '/' . $mland_template );
}
}
return $template;
}
--
The note was created from a comment.