How to Create Custom Page Templates in WordPress

Create custom page templates in WordPress

Different pages often need different layouts: a full-width landing page, a contact page without a sidebar, a page with a list of team members. A page template is a theme file that the editor can choose for a single page in the admin, without any code on their side.

Problem: One page needs a layout that differs from the theme’s default page.php.

Solution: Create a PHP file in the theme with a Template Name: header comment. WordPress finds it and shows it in the Template dropdown of the page editor.

The template file

Create, for example, page-templates/full-width.php in the theme:

<?php
/**
 * Template Name: Full Width
 */

get_header();
?>
<main id="main" class="site-main full-width">
    <?php
    while ( have_posts() ) {
        the_post();
        get_template_part( 'template-parts/content', 'page' );
    }
    ?>
</main>
<?php
get_footer();

After saving the file, open a page in the admin: Page Attributes → Template now lists “Full Width”.

WordPress looks for template headers in the root of the theme and one folder level deeper, so page-templates/full-width.php works, templates/pages/full-width.php does not.

Templates for posts and custom post types

Since WordPress 4.7 a template can also be offered for other post types with the Template Post Type header:

<?php
/**
 * Template Name: Sidebar Left
 * Template Post Type: page, post, portfolio
 */

Template by name or by slug

Do not confuse a page template with the template hierarchy. A file called page-contact.php is used automatically for the page with the slug contact, nobody has to choose it. A file with Template Name can be chosen for any page. Use the first for one fixed page, the second for a layout that several pages share.

Checking the template in code

<?php
if ( is_page_template( 'page-templates/full-width.php' ) ) {
    // for example, do not load the sidebar scripts
}

The path is relative to the theme folder. How to check that a page uses no custom template at all is shown in checking the default page template.

NOTE: The chosen template is stored in the _wp_page_template meta field of the page. If you rename or move the file, the pages keep the old path and quietly fall back to page.php, so after renaming, choose the template on those pages again.