Creating Custom Page Templates
basix

Creating Custom Page Templates

Tutorial Details
  • Program: WordPress
  • Version (if applicable): 3.0+
  • Difficulty: Intermediate (requires knowledge of WordPress templates to make proper use of)
  • Estimated Completion Time: 30 minutes

Pages are hugely useful when using WordPress as a CMS, and when you’re making a website, it’s not uncommon for two pages to have entirely different layouts. Sometimes an if statement will do the trick; if not, you’ll need a custom page template.


Why use a custom page template?

A custom page template is a file located in your theme directory. With it, you can change the layout of a page or show different content to the standard page template (page.php). You can have an unlimited amount of page templates, and choosing the template you’d like to use for a particular page is as easy as selecting an existing template from a drop-down in the WordPress page editor.

Sometimes it might be unnecessary to create a custom page template. For example, say your page.php file, which is used to render all of the Pages on your website, has a function call that shows social networking icons, like so:

	<?php social_networking_icons(); ?>

Say you had a ‘Contact’ page on this website, and on that ‘Contact’ page you didn’t want to show the social networking icons. You could, of course, create a custom page template called ‘Contact Page’ and not include the social networking icons function call on it. However, a simpler method would simply be to wrap the function call in an if statement which showed the icons if the page you were on was not the ‘Contact’ page, like so:

	<?php if(!is_page('Contact')) {
	   social_networking_icons();
    } ?>

It is often worth considering whether the functionality you desire would be simpler to achieve by using a couple of if statements.

A perfect example of a popular use for a custom page template is a ‘full-width’ page. A vast majority of WordPress templates have two or three columns: one ‘main content’ column where post/page content is held, and one or two sidebars that display widgets and calls to action. Sometimes a user will want to take advantage of the full-width of the container those columns are held within, and choose to omit the sidebar column(s) in favor of increasing the size of the ‘main content’ column. Pages that feature media such as image galleries or videos will often benefit from this type of custom page template.

Creating a custom page template can be a simple or difficult operation, depending on the functionality you intend to achieve. Having a well-coded theme helps; HTML elements are often being opened in one file and closed in another, and if the code isn’t structured or organized well then using custom page templates effectively can become a grueling task!


How to create a custom page template

Note that these changes will affect the layout of your page, so making these changes on a live website could cause users to see errors and anomalies. It is best to practice these changes on a private website, or after putting your website in a maintenance mode. Backing up your data ‘just in case’ is always recommended, too.

All custom page templates must start with the following code. It tells WordPress that the file is a custom page template, and sets the name of the template.

	<?php /* Template name: My Custom Page Template */ ?>

Of course, ‘My Custom Page Template’ can be changed to any name you like!

File Naming Convention

Theme Files

As an aside, it is best practice to name your custom page template files with the prefix ‘page_’ (‘page_contact.php’, ‘page_fullwidth.php’). It groups all of the page templates together in your theme directory.

I think the quickest way to get stuck in to custom page templates is to simply copy the code from your standard page.php file into a new file, and make the new file a custom page template. That way you can modify and delete code and see the affect it has on a page. Let’s do that now!

  1. In your code editor, create a new file in the directory of the theme you are currently using. Call it ‘page_test.php’.
  2. At the top of the file, insert the following code:
            	<?php /* Template name: Test */ ?>
            
  3. Open the existing page.php file within the theme you are currently using.
  4. Select all of the code and copy it to the clipboard.
  5. Paste the copied code beneath the code you just inserted
  6. Save the file. Upload it to your theme directory where applicable.
  7. Login to WordPress and edit the page you would like to use to try your new page template on (this can always be reverted, and we won’t be modifying the content of the page itself, so you won’t lose any data saved on the page).
  8. Under ‘Page Attributes’ (usually found on the right-hand side of the editor), select ‘Test’ from the ‘Template’ drop-down.
  9. Update/Publish your page.

Now when you view your page, it should look exactly the same! That’s because we haven’t done anything to customize our custom page template yet! But it’s good to see that the page is still working. If you get an error, make sure you copied the code correctly.

To confirm that your page is using the new ‘page_test.php’ file rather than ‘page.php’, delete any chunk of code from ‘page_test.php’ (‘the_content();’ is usually a good bit to delete), then save (and upload) it. Refresh the page on your website, and the bit you deleted should be missing. If it us, undo the change you made and save (and upload) again. If not, check that you copied the code from this tutorial and the page.php file correctly.

From here you are open to a world of possibilities! As long as that ‘Template name:’ code stays at the top of the file, you can do what ever you like! Your page template doesn’t have to use WordPress syntax, it could simply be a static HTML template – anything you like!


Creating a ‘full-width’ custom page template

As a bit of a bonus, I will cover the common steps involved in creating a full-width custom page template. These steps may not be accurate based on the code in your theme, but you should be able to get the gist of it.

Start by creating a new file called ‘page_fullwidth.php’. Add the below code to the very top, then copy and paste the code from your ‘page.php’ file below it, as before.

	<?php /* Template name: Full Width */ ?>

I’m going to assume that somewhere within the code in that file is the following:

	get_sidebar(); 

If so, remove it – every instance of it if necessary. If it’s contained within any elements, like divs, which may affect the layout of the page – delete those too. An amount of trial and error is often involved in these things if you didn’t create the theme yourself.

I’m also going to assume that the HTML content of the page begins with a div that has a CSS declaration that sets the width, and perhaps floats it left or right. In the themes I create, usually I would have a div with an id of ‘pagecontent’. ‘left’, ‘content’ or ‘post’ are popular alternatives, but you’ll have to investigate! To that div, add the class ‘fullwidth’. Save (and upload) the file. Don’t forget to also set one of your pages in WordPress to use the template.

Open the ‘style.css’ file in your theme. Preferably in a logical place, but it doesn’t really matter (as long as it doesn’t interfere with any other declarations), add the following code:

	.fullwidth {width: 100%;}

Save (and upload) ‘style.css’, then load the page you assigned the ‘Full Width’ template to. You can go back and adjust the CSS declaration if necessary, but hopefully the column that holds your page content will have expanded to fill a larger space. If it hasn’t, it’s entirely down to how your theme has been written. If you are using a premium theme, it may be worth checking the documentation or contacting the developer. Otherwise, feel free to post troubleshooting queries in the comments below, and I’ll do my best to give you any tips.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.iteracion.cl felipe saavedra

    muchas gracias, me será muy útil.

    saludos,
    Felipe…

  • http://www.timhaslam.com TH

    Did you know if you label your files ‘page-templatename.php’, WordPress will automatically use that template if the slug matches? For example, if I am making an About page, I can name my file page-about.php and then when I create the page, if the slug is ‘about’ it will automatically use that template? Pretty handy.

    • Dan Davies
      Author

      Didn’t know that – thanks for the tip!

      • http://cinitriqs.deviantart.com CiNiTriQs

        aaah, the sweet sweet possibilities of wordpress :D so vast and luckily not so misunderstood anymore, go wp for CMS!!!

    • Piyush Sood

      thanks for the tip ;-)

  • mikemick

    Why not recommend dashes instead of underscores? When going down the template hierarchy, WordPress automatically looks for page-[slug].php, no need to assign the page template in the WordPress backend. Not saying you should do this for every custom page type, but it makes sense to do it for some pages, and if you are going to do it for some, you might as well adhere to a single naming convention.

    Also, I’m not sure if it is a typo, but there are html comment elements mixed in with your template name declaration. Was that intentional?

    • mikemick

      Ah, the previous comment wasn’t published when I posted mine.

  • http://webmastersintexas.com Jerry Lee

    Page Templates are a powerful resource. I appreciate the information on the if statement. I am still working on those, and finding them quite powerful.

  • http://www.kreativtheme.com Kreativ Theme

    I was really thing on learning more on WP Custom Pages and Custom Post Type and this tutorial is really great for the start.

    Thanks for another useful tut :)

    • Dan Davies
      Author

      Thanks :-)

  • http://webania.net Ellioy

    I usually use if {} else{} statement for making different views for my pages. So i use just one default page.php and custom codes in it. But page templates are better in some cases, it is true. After this post i will try with it, may be i will like it :)

    • Dan Davies
      Author

      I can see the advantages of just using if/else statements, but when you’re building WordPress websites for clients, custom page templates are vital.

      I’m not horribly fond of giving clients an ‘Administrator’ role to the website (it’s unnecessary), and telling them to add a pageid to an if statement is a scary thought!

      • http://www.inglesnarede.com.br Renato Alves

        I agree with you. When we are managing our own sites/blogs it is acceptable this kind of usage. But for clients the easier the better.

        Great piece of writing. :)

  • http://gods-of-art.com S3bY

    This is great! Just what I was looking for in order to improve my website!

  • Pingback: Digest for web developers #1 « Webania.net – Yet another web developer blog

  • http://www.guillaumevoisin.fr/ Guillaume

    Page templates are awesome.
    But to change the page’s layout, I’d rather create some meta boxes where you can choose let’s say Content + Sidebar or Sidebar + Content or just Content (full width) for the current page and then switch between thoses options directly in page.php template, so that you don’t come up with too many templates pages because you’ve got many layout configurations.

    I’d rather use page templates to display different types of content, for example a template-blog.php page which displays blogs posts or template-portfolio which displays portfolio items and so on.

    But this article is a good start to embrace all the possibilities of page templates ! Thx

    • dj

      Good. How about writing a tutorial on how you write the code to accomplish that – controlling page width by using meta information. That seems like a much more semantic way to handle mere page width to me. Good point.

    • http://www.webmentor.cr/ Marco Berrocal

      Hello Guillerme,

      Do you know where I can get a SIMPLE tutorial on these? I am following this one:

      http://www.deluxeblogtips.com/2010/04/how-to-create-meta-box-wordpress-post.html

      But I can’t get them to display all at once.

  • http://www.StephenRenney.com StephenRenney

    Film | Photography | Design

  • Pingback: Highly Recommended

  • http://vkmediamanagement.com Vanessa

    I am new at developing WordPress themes and have more a Graphic Design background therefore editing images was the only way I knew how to customise templates. This tute is so helpful as I have been trying to find someone to build my page templates that I have designed but have run into so many amateur (Odesk) issues, making it harder for me to fix. So I really value that you have out this put this up.

    Cheers

    Vanessa

  • Pingback: Use WordPress RSS Widget Anywhere In Your Theme | Wptuts+

  • Pingback: My Stream » Add the WordPress RSS Feed Anywhere In Your Theme

  • mark shirley

    Hi tried the widepage template out in twenty eleven child theme and it doesnt work I used to be able to create a widepage template in twenty ten but as yet haven’t found one tutorial that works on twenty eleven.

    • http://www.wayneseddon.co.uk Wayne Seddon

      Worked for me in Twentyelven…

  • Pingback: CRMFRSH / Products and webdesign trends » WH#018 / NOVEMBER.17

  • Pingback: How to Make a Splash Page with WordPress | Wptuts+

  • Pingback: My Stream » How to Make a Splash Page with WordPress

  • http://www.dannetherton.co.uk Dan Netherton

    Very helpful and well put together!

    Thanks!

  • Pingback: How to Make a Splash Page with WordPress | Graphfucker

  • http://www.webtemplates-creare.com/ Paul Weston

    I am from a Graphic Design background have just moved into the world of web. WordPress is very new to me and I am just starting to look into using it. I have been spending time looking for articles and resources I can use to help me with my learning. This had been a great article and one I will be using in the future for my development with WordPress. Great article with great detail

  • Anubis

    Hello there,

    Thanks for an informative article.

    I am actually familiar with how to do what is described here however my problem is bit of an odd one.

    When I create the page template named “page-blog.php” and assign that to the page where all the blog posts are shown it doesn’t apply itself to that page. As you can imagine, as suggested here, even if I didn’t assign the above named template to this page it should still be picked up by WP since the template is named conventionally for WP to do that.

    Any ideas?

  • Pingback: most Popular wordpress tutorial part:1 | Write For Share

  • Pingback: Re-Use Common Elements the Easy Way with Wordpress's get_template_part() Function | Wptuts+

  • Pingback: My Stream » Re-Use Common Elements the Easy Way with WordPress’s get_template_part() Function

  • Pingback: Trucchi, Tecniche e Tutorial Wordpress : i migliori del 2011

  • Pingback: Organizing and Naming Your Themes' Template Files for Clarity and Convenience | Wptuts+

  • Pingback: My Stream » Organizing and Naming Your Themes’ Template Files for Clarity and Convenience

  • http://www.islamforuniverse.com mohammad

    an awesome and fantastic tutorial you are given there man!
    just cheers ;)

  • http://codecanyon.net/user/nickys Nikolay Dyankov

    One thing that I’ve been trying to find out is – how can I add custom fields ONLY for a specific template? For example, in the “services” page template I want to have 2 more editors, but I don’t want to add them for each page.

  • http://webdesignerbd.com/ Faisal Islam

    Thank you very much. You show a clear way to create custom layout of an existing themes. :-)

  • Pingback: Custom Blog Page For WordPress How To Make a Custom Blog Page

  • Brian

    Hi Dan,
    This maybe a little off topic but wanted to see if you could help shed some light. What would you do if you needed to change the width of a certain css class but only on a specific page, leaving the rest of the pages using the default? Would you use an if than statement or a hook to remove and add in new class? Or am I totally off.

    Thanks in advance

    • http://twitter.com/planetabhi Abhimanyu Rana

      Use plugin Custom-CSS for that specific page.

  • http://www.wayneseddon.co.uk Wayne Seddon

    Hi. I’ve created a custom page template no problem – thanks to this tutorial. But I want to take it a step further…

    I want to create a custom header (but keep the original too) and have the new template call the custom header but I’m not sure how.

    So far I’ve copied the header.php file and made my changes. I’ve created the custom template file but I don’t know how to pull in the new header…

    Does this make sense? Are there any tutorials explaining how to do this?

  • sam

    Awesome tuts. need more on that.

  • http://www.facebook.com/sangdiago Sang Beo

    helllo!

  • Pingback: Creación de páginas personalizadas en Wordpress

  • kirit

    hi

    i need information related “how we can create a contact us template option in weordpress and how we can add new templated in wordpress

  • http://twitter.com/planetabhi Abhimanyu Rana

    Thanks for share.

  • http://www.facebook.com/iridescent.sovo Iridescent Sovo

    Awesome tuts.

  • Pingback: How I Created My New Archives Page

  • http://www.facebook.com/john.baughman.754 John Baughman

    This is exactly what I need to do. I want to create a full-width custom page template. But the code in my page.php does not contain “get sidebar” or anything else that you discuss in your tutorial. This is the code:

    <div class="post" id="post-”>

    <?php the_content('Read the rest of this page »’); ?>

    Pages: ‘, ‘after’ => ”, ‘next_or_number’ => ‘number’)); ?>

    <?php edit_post_link('Edit this entry.', '’, ”); ?>

    Any suggestions for how I can proceed?
    Thanks.
    John

    • http://www.facebook.com/john.baughman.754 John Baughman

      Oops. The code didn’t past very well. I’m embarrassed. I’ll try again now that I’ve read the posting instructions.

      <div class="post" id="post-">

      <?php the_content('Read the rest of this page »'); ?>

      'Pages: ', 'after' => '', 'next_or_number' => 'number')); ?>

      <?php edit_post_link('Edit this entry.', '', ''); ?>

  • Pingback: Hướng dẫn Custom Post Type toàn tập – Phần 1

  • Pingback: Hướng dẫn Custom Post Type toàn tập – Phần 1 | Download Full Mediafire, Hướng Dẫn, Thủ ThuậtFull Download, Crack, Keygen, Patch, Serials, Movie Full HD, Torrent, Mediarire

  • Pingback: Hướng dẫn Custom Post Type toàn tập – Phần 1 | Thiết Kế Website - Thiết Kế Website Giá Rẻ - Seo Website Giá Rẻ - Seo website