I need a page template to be used with my plugin. I don’t need to replace a theme template such as single or archive.
Normally I’d use
/*
* Template Name: Blah Blah Blah
*/
to add a template to the page options, however, this isn’t working in the plugin, as expected. I know how to add a template for a custom post type in a plugin. However, I need this to be an option the templates dropdown in the page options.
Here is a fairly simple approach I was able to get working within a plugin. You’ll want to reference https://developer.wordpress.org/reference/hooks/theme_page_templates/ and https://developer.wordpress.org/reference/hooks/template_include/ as you review the code below.
<?php
//Add our custom template to the admin's templates dropdown
add_filter( 'theme_page_templates', 'pluginname_template_as_option', 10, 3 );
function pluginname_template_as_option( $page_templates, $theme, $post ){
$page_templates['template-landing.php'] = 'Example Landing Page';
return $page_templates;
}
//When our custom template has been chosen then display it for the page
add_filter( 'template_include', 'pluginname_load_template', 99 );
function pluginname_load_template( $template ) {
global $post;
$custom_template_slug = 'template-landing.php';
$page_template_slug = get_page_template_slug( $post->ID );
if( $page_template_slug == $custom_template_slug ){
return plugin_dir_path( __FILE__ ) . $custom_template_slug;
}
return $template;
}