WordPress provides a default template for page creation. That may not be sufficient for our needs in certain situations. In our WordPress installation we may have a need to group a set of pages and display them in a common layout. Similarly we may have to create multiple different layout groups. In such a situation the custom page template option provided by WordPress will be handy. In this article, I will explain with details to help you create a custom page template using WordPress.
In general, we will have a custom page template provided by default in WordPress. Check the file page.php from your theme and it is used as the layout for all the pages you create in WordPress. This is about WordPress pages and not the posts. This page.php template file is used as the wireframe to create all the pages and display it. In the following code example let us see how to create such a custom page template and use it to publish a new page. In a previous article we have learnt about create a WordPress widget, refer that if you are looking for creating widgets.
The custom page template is an usual PHP file with one difference. It has a specific structure and it is header and content body. The template header is defined just by a comment and anything followed by that is the template body. Following screen shot show the default page.php from the Twenty_Seventeen theme available as part of the WordPress.
When we create a new custom page, we need to define a template name as follows.
<?php /* Template Name: Contact Template */ ?>
The above comment should be the start of your custom template. This line is to inform the WordPress that this is a custom page template. Create a simple PHP page and paste the above one line and save it. Followed by that comment line, for now lets have a “Hello World!” text in HTML paragraph tag. Then save that with the file name “contact-template.php” and upload it to your theme folder.
Now we have created a WordPress custom page template and let us see how to use it. Go to “Add New Page” and see the side bar widget “Page Attributes” There will be a drop-down list labeled “Template“. In that drop down list, our new template will appear as “Contact Template” and that is the name of the template we declared in top of the page template file.
Select that new template that we have created and as usual you can add content to the page in the content area and Publish the page. You can see the new page will have “Hello World” text and that will have the layout as defined in this new custom template page.
This is just an example, in real-time we can have two to three templates and each template will have different layouts. For example,
It is important to not that there is a hierarchy using which the WordPress decides which template should be used to display. WordPress looks for the template file in the following order.