Posted in PHP

Add a custom page template to WordPress

We’d like to provide one of our upcoming themes with multiple screen layouts, for this we’re going to add two custom templates:

  • Fullwidth: a fullwidth page
  • Contained: a boxed layout with a max-width column of content in the center of the screen.

To add a custom page template we will first clone page.php (in our theme directory). In this example we’ll call ours template-fullwidth.php.

Once cloned, replace the contents of the top of the file.
You’ll want to replace everything between the `get_header();` and the opening PHP tag with the following:

/* Template Name: Fullwidth
 * @package THEME_SLUG_HERE
 */

Now our new template will be available within WordPress, select the page template from the right side when editing a page:

Awesome, now your page will use the new template.

Expand the content to full width:

Now we’re going to make the content wider than the template.
Each theme may be slightly different, find the container that’s forcing the contained width. In our case it’s the <div> below the closing of the page <header> section.

Note the following CSS which is used on the theme, this is what’s restricting the width of our content:

div#content {
    margin: 100px auto 0;
    width: 1000px;
}

To edit the layout we’re going to use CSS which is more specific.
If you’d like more information on CSS specificity, check out this article.

To be more ‘specific’ we’re going to add another class to the front of the CSS, we’ll then add this CSS to the theme.
Without being more specific our CSS may be overwritten by the themes CSS..

Note above the CSS classes that have been applied to the <body> tag. Due to the template we added, you’ll now see ‘page-template-template-fullwidth’ as one of the classes applied (thanks WordPress!).

So, we’ll prefix the CSS with the class .page-template-template-fullwidth and it’s more specific than the theme’s original styles:

.page-template-template-fullwidth div#content {
    width: 100;
}

In our theme we’d like to leave a small gap between the edges of the screen and the content, giving the content a 20px buffer on either side:

.page-template-template-fullwidth div#content {
    width: 100%;
    padding: 0 20px;
}

See below, our new CSS is overwriting the CSS style for ‘width’ that the theme declared:

All done, happy templating!

Leave a Reply

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