Custom Template pages have an important role in WordPress. There are thousands of themes on WordPress and each theme has its own unique templating. But most of the time we need some different templates or layouts that are not available in the theme. Because every theme has pre-defined templates and layouts.
The custom template page is not only about the design or look of the page we can do other things as well. Let’s say if a client needs to print all the events on the page which is coming from a custom post type and there should be a restriction that only the login user can see the list of events. so we can do this easily by using the custom page template and put the login restriction on Php code level.
How to Create a Custom Page Template?
The template page is the part of the theme so first we go to the theme directory and create a new php file “my-template.php” ( you can create with any name ) in the theme directory, open the file in the editor which you like, and add template header in it.
<?php
/**
* Template Name: My Template
**/
When you add a header in the file you can see the Templating option under the Page Attribute section in your WordPress pages.
Edit Your Custom Template Page
Then the next thing you should call header and footer in this template.
for adding header you must call get_header() function and get_footer() for adding footer in our template page.
<?php
/**
* Template Name: My Template
**/
get_header();
get_footer();
Then we have to call the content of the template page, for doing this open page.php file in the editor and copy all it’s content except header and footer. So now your template page something look like this
<?php
/**
* Template Name: My Template
**/
?>
<?php get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php
// Start the loop.
while ( have_posts() ) : the_post();
// Include the page content template.
get_template_part( 'template-parts/content', 'page' );
// If comments are open or we have at least one comment, load up the comment template.
if ( comments_open() || get_comments_number() ) {
comments_template();
}
// End of the loop.
endwhile;
?>
</main><!-- .site-main -->
<?php get_sidebar( 'content-bottom' ); ?>
</div><!-- .content-area -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
Link Your Custom Template Page to Any WordPress Page
Now save your custom page template file then open your WordPress dashboard and add a new page, select the template “My Template” from the Page Attribute section and publish it, When you view the page on the front-end that page will load as per your template file.
You can customize this template in your own way. you can put any WordPress or Php functions to make it more powerful according to your requirements.