How To Add Page Template From Plugin in WordPress

The ability to assign different page templates to pages is a great feature WordPress has. But if you are a plugin developer and you don’t have access to the theme then it is difficult to add a page template for the website. Because we know that we can create page templates within theme files itself.

In this article, you’ll learn how you can add page templates from a plugin and later in this article there is another bonus code snippet related to this feature.

Add Page Template from Plugin

To start developing, first, we’ll create a new plugin and add the codes below.

With this code, we can able to filter the list of page templates for the theme. To add the page template we need to first create the template file and have that file within the templates directory in the plugin directory. Now create the function with the file path for the template file.

Add Page Template to Dropdown List

After adding these codes, we can see a new page template is showing in the template dropdown list. Now if we publish the page with this newly created template selected, then we can see it is showing the default template from the theme.

Now, we have to save this template information after publishing/updating the page. To do this add this code snippet to the plugin file.

This filter hook executed before WordPress includes a template file, so this can be used to override WordPress’s default template behavior. We’ll do exactly that in the function, here’s the function code.

Here, we are returning the path of the template file which we have set up previously while adding the page template to the dropdown list.

Now after adding these codes to our plugin we can see the template is applied through the plugin properly and this template file is located at templates directory within our plugin directory.

BONUS: Remove Parent Theme Style from Custom Template Page

There are many cases where you need to use wp_head and wp_footer function in your template file to get benefits of other plugins. In this case style of the current theme will also apply to your template and this may cause CSS confliction. To avoid any kind of CSS design confliction we may need to remove theme CSS file from our page.

This code will fetch the information of active theme and from that, we’ll get the stylesheet info and remove it for the page.

So here’s the complete code of our final plugin.

So this is it. It is the complete code for the plugin which adds page template.

Leave a Reply

Your email address will not be published. Required fields are marked *