In this tutorial, we’ll learn how to add a custom page template from your WordPress plugin using two essential filters: theme_page_templates
and template_include
.
Step 1: Add Template file
First, create a new folder named templates
in your plugin’s directory. This is where we’ll store our custom page template file.
Next, create a new file named page-template.php
inside the templates
folder. This file will contain the markup and code for your custom page template.
Step 2: Adding the Custom Page Template to the Dropdown
Then, we need to hook into the theme_page_templates
filter, which allows us to add our custom page template to the dropdown in the Page Attributes meta box
We define the mukto_add_page_template_to_dropdown
function, which will add our custom page template to the available templates array:
add_filter('theme_page_templates', 'mukto_add_page_template_to_dropdown');
function mukto_add_page_template_to_dropdown($templates)
{
$template_path = plugin_dir_path(__FILE__) . 'templates/page-template.php';
$templates[$template_path] = __('Page Template Name', 'text-domain');
return $templates;
}
Step 3: Changing the Page Template When the Page Update
After adding our custom page template to the dropdown, we need to hook into the template_include
filter to change the page template when rendering a page that has our custom template assigned
The mukto_change_page_template
function checks if the current request is for a page, and if so, it retrieves the post meta data for the current page:
add_filter('template_include', 'mukto_change_page_template', 99);
function mukto_change_page_template($template)
{
if (is_page()) {
$meta = get_post_meta(get_the_ID());
if (!empty($meta['_wp_page_template'][0]) && $meta['_wp_page_template'][0] != $template) {
$template = $meta['_wp_page_template'][0];
}
}
return $template;
}
Usage
After adding the code snippets to your plugin file, you’ll see your custom page template available in the Page Attributes meta box when editing or creating a new page in the WordPress admin area.
To use the custom page template, simply select it from the dropdown in the Page Attributes meta box, and WordPress will load your custom template file (templates/page-template.php
) when rendering that specific page.
In the templates/page-template.php
file, you can define your custom page template markup, including any specific layouts, functionality, or content structures you require.
<?php
// Your custom page template code goes here
get_header();
// ... Your custom content and markup ...
get_footer();
By following this approach, you can easily add custom page templates from your WordPress plugin, providing users with more flexibility and control over the appearance and functionality of their pages.