Menu Search
Jump to the content X X
Smashing Conf New York

We use ad-blockers as well, you know. We gotta keep those servers running though. Did you know that we publish useful books and run friendly conferences — crafted for pros like yourself? E.g. upcoming SmashingConf Barcelona, dedicated to smart front-end techniques and design patterns.

A Detailed Guide To WordPress Custom Page Templates

I like to think of WordPress as the gateway drug of web development. Many people who get started using the platform are initially merely looking for a comfortable (and free) way to create a simple website. Some Googling and consultation of the WordPress Codex1 later, it’s done and that should be it. Kind of like “I’m just going to try it once.”

However, a good chunk of users don’t stop there. Instead, they get hooked. Come up with more ideas. Experiment. Try out new plugins. Discover Firebug2. Boom. Soon there is no turning back. Does that sound like your story? As a WordPress user it is only natural to want more and more control over your website. To crave custom design, custom functionality, custom everything.

Luckily, WordPress is built for exactly that. Its flexible structure and compartmentalized architecture allows anyone to change practically anything on their site.

Among the most important tools in the quest for complete website control are page templates. They allow users to dramatically alter their website’s design and functionality. Want a customized header for your front page? Done. An additional sidebar only for your blog page? No problem. A unique 404 error page3? Be. My. Guest.

If you want to know how WordPress page templates can help you achieve that, read on. But first, a little background information.

Template Files In WordPress Link

What are we talking about when we speak of templates in the context of WordPress? The short version is that templates are files which tell WordPress how to display different types of content.

The slightly longer version: every time someone sends a request to view part of your website, the WordPress platform will figure out what content they want to see and how that specific part of your website should be rendered.

For the latter, WordPress will attempt to use the most appropriate template file found within your theme. Which one is decided on the basis of a set order, the WordPress template hierarchy4. You can see what this looks like in the screenshot below or in this interactive version5.

The WordPress template hierarchy.6
The WordPress template hierarchy. (Image credit: WordPress Codex7)(View large version8)

The template hierarchy is a list of template files WordPress is familiar with that are ranked to determine which file takes precedence over another.

You can think of it as a decision tree. When WordPress tries to decide how to display a given page, it works its way down the template hierarchy until it finds the first template file that fits the requested page. For example, if somebody attempted to access the address http://yoursite.com/category/news, WordPress would look for the correct template file in this order:

  1. category-{slug}.php: in this case category-news.php
  2. category-{id}.php>: if the category ID were 5, WordPress would try to find a file named category-5.php
  3. category.php
  4. archive.php
  5. index.php

At the bottom of the hierarchy is index.php. It will be used to display any content which does not have a more specific template file attached to its name. If a template file ranks higher in the hierarchy, WordPress will automatically use that file in order to display the content in question.

Page Templates And Their Use Link

For pages, the standard template is usually the aptly named page.php. Unless there is a more specific template file available (such as archive.php for an archive page), WordPress will use page.php to render the content of all pages on your website.

However, in many cases it might be necessary to change the design, look, feel or functionality of individual parts of your website. This is where page templates come into play. Customized page templates allow you to individualize any part of your WordPress site without affecting the rest of it.

You might have already seen this at work. For example, many WordPress themes today come with an option to change your page to full width, add a second sidebar or switch the sidebar’s location. If that is the case for yours, it was probably done through template files. There are several ways to accomplish this and we’ll go over them later.

First, however, a word of caution: since working with templates involves editing and changing files in your active theme, it’s always a good idea to go with a child theme when making these kinds of customizations. That way you don’t run the danger of having your changes overwritten when your parent theme gets updated.

How To Customize Any Page In WordPress Link

There are three basic ways to use custom page templates in WordPress: adding conditional statements to an existing template; creating specific page templates which rank higher in the hierarchy; and directly assigning templates to specific pages. We will take a look at each of these in turn.

Using Conditional Tags In Default Templates Link

An easy way to make page-specific changes is to add WordPress’s many conditional tags9 to a template already in use. As the name suggests, these tags are used to create functions which are only executed if a certain condition is met. In the context of page templates, this would be something along the line of “Only perform action X on page Y.”

Typically, you would add conditional tags to your theme’s page.php file (unless, of course, you want to customize a different part of your website). They enable you to make changes limited to the homepage, front page, blog page or any other page of your site.

Here are some frequently used conditional tags:

  1. is_page(): to target a specific page. Can be used with the page’s ID, title, or URL/name.
  2. is_home(): applies to the home page.
  3. is_front_page(): targets the front page of your site as set under Settings → Reading
  4. is _category(): condition for a category page. Can use ID, title or URL/name like is_page() tag.
  5. is_single(): for single posts or attachments
  6. is_archive(): conditions for archive pages
  7. is_404(): applies only to 404 error pages

For example, when added to your page.php in place of the standard get_header(); tag, the following code will load a custom header file named header-shop.php when displaying the page http://yoursite.com/products.

if ( is_page('products') ) {
  get_header( 'shop' );
} else {
  get_header();
}

A good use case for this would be if you have a shop on your site and you need to display a different header image or customized menu on the shop page. You could then add these customization in header-shop.php and it would show up in the appropriate place.

However, conditional tags are not limited to one page. You can make several statements in a row like so:

if ( is_page('products') ) {
  get_header( 'shop' );
} elseif ( is_page( 42 ) ) {
  get_header( 'about' );
} else {
  get_header();
}

In this second example, two conditions will change the behavior of different pages on your site. Besides loading the aforementioned shop-specific header file, it would now also load a header-about.php on a page with the ID of 42. For all other pages the standard header file applies.

To learn more about the use of conditional tags, the following resources are highly recommended:

Creating Page-Specific Files In The WordPress Hierarchy Link

Conditional tags are a great way to introduce smaller changes to your page templates. Of course, you can also create larger customizations by using many conditional statements one after the other. I find this a very cumbersome solution, however, and would opt for designated template files instead.

One way to do this is to exploit the WordPress template hierarchy. As we have seen, the hierarchy will traverse a list of possible template files and choose the first one it can find that fits. For pages, the hierarchy looks like this:

  • Custom page template
  • page-{slug}.php
  • page-{id}.php
  • page.php
  • index.php

In first place are custom page templates which have been directly assigned to a particular page. If one of those exists, WordPress will use it no matter which other template files are present. We will talk more about custom page templates in a bit.

After that, WordPress will look for a page template that includes the slug of the page in question. For example, if you include a file named page-about.php in your theme files, WordPress will use this file to display your ‘About’ page or whichever page can be found under http://www.yoursite.com/about.

Alternatively, you can achieve the same by targeting your page’s ID. So if that same page has an ID of 5, WordPress will use the template file page-5.php before page.php if it exists; that is, only if there isn’t a higher-ranking page template available.

(BTW, you can find out the ID for every page by hovering over its title under ‘All Pages’ in your WordPress back-end. The ID will show up in the link displayed by your browser.)

Assigning Custom Page Templates Link

Besides providing templates in a form that WordPress will use automatically, it is also possible to manually assign custom templates to specific pages. As you can see from the template hierarchy, these will trump any other template file present in the theme folder.

Just like creating page-specific templates for the WordPress hierarchy, this requires you to provide a template file and then link it to whichever page you want to use it for. The latter can be done in two different ways you might already be familiar with. Just in case you aren’t, here is how to do it.

1. Assigning Custom Page Templates From The WordPress Editor Link

In the WordPress editor, you find an option field called ‘Page Attributes’ with a drop-down menu under ‘Template’.

Page Attributes in the WordPress editor.12
Page Attributes in the WordPress editor. (View large version13)

Clicking on it will give you a list of available page templates on your WordPress website. Choose the one you desire, save or update your page and you are done.

Available templates under Page Attributes.14
Available templates under Page Attributes. (View large version15)
2. Setting A Custom Template Via Quick Edit Link

The same can also be achieved without entering the WordPress editor. Go to ‘All Pages’ and hover over any item in the list there. A menu will become visible that includes the ‘Quick Edit’ item.

Click on it to edit the page settings directly from the list. You will see the same drop-down menu for choosing a different page template. Pick one, update the page and you are done.

Not so hard after all, is it? But what if you don’t have a custom page template yet? How do you create it so that your website looks exactly the way you want it? Don’t worry, that’s what the next part is all about.

A Step-By-Step Guide To Creating Custom Page Templates Link

Putting together customized template files for your pages is not that hard but here are a few details you have to pay attention to. Therefore, let’s go over the process bit-by-bit.

1. Find The Default Template Link

A good way is to start by copying the template which is currently used by the page you want to modify. It’s easier to modify existing code than to write an entire page from scratch16. In most cases this will be the page.php file.

(If you don’t know how to find out which template file is being used on the page you want to edit, the plugin What The File17 will prove useful.)

I will be using the Twenty Twelve theme for demonstration. Here is what its standard page template looks like:

<?php
/**
 * The template for displaying all pages
 *
 * This is the template that displays all pages by default.
 * Please note that this is the WordPress construct of pages
 * and that other 'pages' on your WordPress site will use a
 * different template.
 *
 * @package WordPress
 * @subpackage Twenty_Twelve
 * @since Twenty Twelve 1.0
 */
get_header(); ?>

  <div id="primary" class="site-content">
    <div id="content" role="main">

      <?php while ( have_posts() ) : the_post(); ?>
        <?php get_template_part( 'content', 'page' ); ?>
        <?php comments_template( '', true ); ?>
      <?php endwhile; // end of the loop. ?>

    </div><!-- #content -->
  </div><!-- #primary -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

As you can see, nothing too fancy here: the usual calls for the header and footer, and the loop in the middle. The page in question looks like this:

The default page template in the Twenty Twelve theme.18
The default page template in the Twenty Twelve theme. (View large version19)

2. Copy And Rename The Template File Link

After identifying the default template file, it’s time to make a copy. We will use the duplicated file in order to make the desired changes to our page. For that we will also have to rename it. Can’t have two files of the same name, that’s just confusing for everyone.

You are free to give the file any name you like as long as it doesn’t start with any of the reserved theme filenames20. So don’t be naming it page-something.php or anything else that would make WordPress think it is a dedicated template file.

It makes sense to use a name which easily identifies what this template file is used for, such as my-custom-template.php. In my case I will go with custom-full-width.php.

3. Customize The Template File Header Link

Next we have to tell WordPress that this new file is a custom page template. For that, we will have to adjust the file header in the following way:

<?php
/*
 * Template Name: Custom Full Width
 * Description: Page template without sidebar
 */

// Additional code goes here...

The name under ‘Template Name’ is what will be displayed under ‘Page Attributes’ in the WordPress editor. Make sure to adjust it to your template name.

4. Customize The Code Link

Now it’s time to get to the meat and potatoes of the page template: the code. In my example, I merely want to remove the sidebar from my demo page.

This is relatively easy, as all I have to do is remove <?php get_sidebar(); ?> from my page template since that’s what is calling the sidebar. As a consequence, my custom template ends up looking like this:

<?php
/*
 * Template Name: Custom Full Width
 * Description: Page template without sidebar
 */

get_header(); ?>

<div id="primary" class="site-content">
  <div id="content" role="main">

    <?php while ( have_posts() ) : the_post(); ?>
      <?php get_template_part( 'content', 'page' ); ?>
      <?php comments_template( '', true ); ?>
    <?php endwhile; // end of the loop. ?>

  </div><!-- #content -->
</div><!-- #primary -->

<?php get_footer(); ?>

5. Upload The Page Template Link

After saving my customized file, it is now time to upload it to my website. Custom page templates can be saved in several places to be recognized by WordPress:

  • Your active (child) theme’s folder
  • The folder of your main parent theme
  • A subfolder within either of these

I personally like to create a folder named page_templates in my child theme and place any customized templates in there. I find this easiest to retain an overview over my files and customizations.

6. Activate The Template Link

As a last step, you need to activate the page template. As mentioned earlier, this is done under Page Attributes → Templates in the WordPress editor. Save, view the page and voilà! Here is my customized page without a sidebar:

Customized page template without the sidebar.21
Customized page template without the sidebar. (View large version22)

Not so hard, is it? Don’t worry, you will quickly get the hang of it. To give you a better impression of what to use these page templates for, I will demonstrate additional use cases (including the code) for the remainder of the article.

Five Different Ways To Use Page Templates Link

As already mentioned, page templates can be employed for many different purposes. You can customize pretty much anything on any page with their help. Only your imagination (and coding abilities) stand in your way.

1. Full-Width Page Template Link

The first case we will look at is an advanced version of the demo template we created above. Up there, we already removed the sidebar by deleting <?php get_sidebar(); ?> from the code. However, as you have seen from the screenshot this does not actually result in a full-width layout since the content section stays on the left.

To address this, we need to deal with the CSS, in particular this part:

.site-content {
  float: left;
  width: 65.1042%;
}

The width attribute limits the element which holds our content to 65.1042% of the available space. We want to increase this.

If we just change it to 100%, however, this will affect all other pages on our site, which is far from what we want. Therefore, the first order here is to change the primary div‘s class in our custom template to something else, like class="site-content-fullwidth". The result:

<?php
/*
 * Template Name: Custom Full Width
 * Description: Page template without sidebar
 */

get_header(); ?>

<div id="primary" class="site-content-fullwidth">
  <div id="content" role="main">

    <?php while ( have_posts() ) : the_post(); ?>
      <?php get_template_part( 'content', 'page' ); ?>
      <?php comments_template( '', true ); ?>
    <?php endwhile; // end of the loop. ?>

  </div><!-- #content -->
</div><!-- #primary -->

<?php get_footer(); ?>

Now we can adjust the CSS for our new custom class:

.site-content-fullwidth {
  float: left;
  width: 100%;
}

As a result, the content now stretches all the way across the screen.

The custom page template at full width.23
The custom page template at full width. (View large version24)

2. Dynamic 404 Error Page With Widget Areas Link

The 404 error page is where every person lands who tries to access a page on your website that doesn’t exist, be it through a typo, a faulty link or because the page’s permalink has changed.

Despite the fact that getting a 404 is disliked by everyone on the Internet, if you are running a website the 404 error page is of no little importance. Its content can be the decisive factor on whether someone immediately abandons your site or sticks around and checks out your other content.

Coding a customized error page from scratch is cumbersome, especially if you are not confident in your abilities. A better way is to build widget areas into your template so you can flexibly change what is displayed there by drag and drop.

For this we will grab and edit the 404.php file that ships with Twenty Twelve (template hierarchy, remember?). However, before we change anything on there, we will first create a new widget by inserting the following code into our functions.php file:

register_sidebar( array(
  'name' => '404 Page',
  'id' => '404',
  'description'  => __( 'Content for your 404 error page goes here.' ),
  'before_widget' => '<div id="error-box">',
  'after_widget' => '</div>',
  'before_title' => '<h3 class="widget-title">',
  'after_title' => '</h3>'
) );

This should display the newly created widget in your WordPress back-end. To make sure that it actually pops up on the site, you need to add the following line of code to your 404 page in the appropriate place:

<?php dynamic_sidebar( '404' ); ?>

In my case, I want to replace the search form (<?php get_search_form(); ?>) inside the template with my new widget, making for the following code:

<?php
/**
 * The template for displaying 404 pages (Not Found)
 *
 * @package WordPress
 * @subpackage Twenty_Twelve
 * @since Twenty Twelve 1.0
 */

get_header(); ?>

<div id="primary" class="site-content">
  <div id="content" role="main">

    <article id="post-0" class="post error404 no-results not-found">
      <header class="entry-header">
        <h1 class="entry-title"><?php _e( 'This is somewhat embarrassing, isn&amp;rsquo;t it?', 'twentytwelve' ); ?></h1>
      </header>

      <div class="entry-content">
        <?php dynamic_sidebar( '404' ); ?>
      </div><!-- .entry-content -->
    </article><!-- #post-0 -->

  </div><!-- #content -->
</div><!-- #primary -->

<?php get_footer(); ?>

After uploading the template to my site, it’s time to populate my new widget area:

404 page template widget.25
404 page template widget. (View large version26)

If I now take a look at the 404 error page, my newly created widgets show up there:

Customized 404 page.27
Customized 404 page. (View large version28)

3. Page Template For Displaying Custom Post Types Link

Custom post types are a great way to introduce content that has its own set of data points, design and other customizations. A favorite use case for these post types are review items such as books and movies. In our case we want to build a page template that shows portfolio items.

We first need to create our custom post type (CPT). This can be done manually or via plugin. One plugin option I can wholeheartedly recommend is Types29. It lets you easily create custom post types and custom fields.

Install and activate Types, add a custom post, make sure its slug is ‘portfolio’, customize any fields you need (such as adding a featured image), adjust any other options, and save.

Now, that we have our portfolio post type, we want it to show up on our site. The first thing we’ll do is create the page in question. Be aware that if you chose ‘portfolio’ as the slug of your CPT, the page can not have the same slug. I went with my clients-portfolio and also added some example text.

Portfolio page without a custom page template.30
Portfolio page without a custom page template. (View large version31)

After adding a few items in the ‘portfolio’ post type section, we want them to show up on our page right underneath the page content.

To achieve this we will again use a derivative of the page.php file. Copy it, call it portfolio-template.php and change the header to this:

<?php
/*
 * Template Name: Portfolio Template
 * Description: Page template to display portfolio custom post types 
 * underneath the page content
 */
 

However, in this case we will have to make a few changes to the original template. When you take a look at the code of page.php, you will see that it calls another template file in the middle, named content-page.php (where it says <?php get_template_part( 'content', 'page' ); ?>). In that file we find the following code:

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
  <header class="entry-header">
    <?php if ( ! is_page_template( 'page-templates/front-page.php' ) ) : ?>
    <?php the_post_thumbnail(); ?>
    <?php endif; ?>
    <h1 class="entry-title"><?php the_title(); ?></h1>
  </header>

  <div class="entry-content">
    <?php the_content(); ?>
    <?php wp_link_pages( array( 'before' => '<div class="page-links">' . __( 'Pages:', 'twentytwelve' ), 'after' => '</div>' ) ); ?>
  </div><!-- .entry-content -->
  <footer class="entry-meta">
    <?php edit_post_link( __( 'Edit', 'twentytwelve' ), '<span class="edit-link">', '</span>' ); ?>
  </footer><!-- .entry-meta -->
</article><!-- #post -->

As you can see, it is here that the page title and content are called. Since we definitely want those on our portfolio site, we will need to copy the necessary parts of this template to our page.php file. The result looks like this:

get_header(); ?>

<div id="primary" class="site-content">
  <div id="content" role="main">

    <?php while ( have_posts() ) : the_post(); ?>
      <header class="entry-header">
        <?php the_post_thumbnail(); ?>
        <h1 class="entry-title"><?php the_title(); ?></h1>
      </header>

      <div class="entry-content">
        <?php the_content(); ?>
      </div><!-- .entry-content -->
      
      <?php comments_template( '', true ); ?>
    <?php endwhile; // end of the loop. ?>

  </div><!-- #content -->
</div><!-- #primary -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

To get the portfolio items onto our page, we will add the following code right beneath the the_content() call.

<?php
  $args = array(
    'post_type' => 'portfolio', // enter custom post type
    'orderby' => 'date',
    'order' => 'DESC',
  );
   
  $loop = new WP_Query( $args );
  if( $loop->have_posts() ):
  while( $loop->have_posts() ): $loop->the_post(); global $post;
    echo '<div class="portfolio">';
    echo '<h3>' . get_the_title() . '</h3>';
    echo '<div class="portfolio-image">'. get_the_post_thumbnail( $id ).'</div>';
    echo '<div class="portfolio-work">'. get_the_content().'</div>';
    echo '</div>';
  endwhile;
  endif;
?>

This will make the CPT show up on the page:

The custom portfolio template.32
The custom portfolio template. (View large version33)

I’m sure we all agree that it looks less than stellar, so some styling is in order.

/* Portfolio posts */

.portfolio {
  -webkit-box-shadow: 0px 2px 2px 0px rgba(50, 50, 50, 0.75);
  -moz-box-shadow:    0px 2px 2px 0px rgba(50, 50, 50, 0.75);
  box-shadow:         0px 2px 2px 0px rgba(50, 50, 50, 0.75);
  margin: 0 0 20px;
  padding: 30px;
}
.portfolio-image {
  display: block;
  float: left;
  margin: 0 10px 0 0;
  max-width: 20%;
}
.portfolio-image img {
  border-radius: 0;
}
.portfolio-work {
  display: inline-block;
  max-width: 80%;
}
.portfolio h3{
  border-bottom: 1px solid #999;
  font-size: 1.57143rem;
  font-weight: normal;
  margin: 0 0 15px;
  padding-bottom: 15px;
}

Much better, don’t you think?

The custom portfolio template with styling.34
The custom portfolio template with styling. (View large version35)

And here is the entire code for the portfolio page template:

<?php
/*
 * Template Name: Portfolio Template
 * Description: Page template to display portfolio custom post types 
 * underneath the page content
 */

get_header(); ?>

<div id="primary" class="site-content">
  <div id="content" role="main">

    <?php while ( have_posts() ) : the_post(); ?>
        
      <header class="entry-header">
        <?php the_post_thumbnail(); ?>
        <h1 class="entry-title"><?php the_title(); ?></h1>
      </header>

      <div class="entry-content">
        <?php the_content(); ?>
        <?php
          $args = array(
            'post_type' => 'portfolio', // enter custom post type
            'orderby' => 'date',
            'order' => 'DESC',
          );
              
          $loop = new WP_Query( $args );
          if( $loop->have_posts() ):
          while( $loop->have_posts() ): $loop->the_post(); global $post;
            echo '<div class="portfolio">';
            echo '<h3>' . get_the_title() . '</h3>';
            echo '<div class="portfolio-image">'. get_the_post_thumbnail( $id ).'</div>';
            echo '<div class="portfolio-work">'. get_the_content().'</div>';
            echo '</div>';
          endwhile;
          endif;
        ?>
      </div><!-- #entry-content -->
      <?php comments_template( '', true ); ?>               
    <?php endwhile; // end of the loop. ?>                
  </div><!-- #content -->
</div><!-- #primary -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

4. Contributor Page With Avatar images Link

Next up in our page template use cases is a contributor page. We want to set up a list of authors on our website, including their images and the number of posts they have published under their name. The end result will look like this:

The completed custom contributors page.36
The completed custom contributors page. (View large version37)

We will again start out with our hybrid file from before and add the code for the contributor list to it. But what if you don’t know how to create such a thing? No worries, you can get by with intelligent stealing.

You see, the Twenty Fourteen default theme comes with a contributor page by default. You can find its template in the page-templates folder with the name contributors.php.

When looking into the file, however, you will only find the following call in there: twentyfourteen_list_authors();. Luckily, as an avid WordPress user you now conclude that this probably refers to a function in Twenty Fourteen’s function.php file and you would be right.

From what we find in there, the part that interests us is this:

<?php
// Output the authors list.
$contributor_ids = get_users( array(
  'fields'  => 'ID',
  'orderby' => 'post_count',
  'order'   => 'DESC',
  'who'     => 'authors',
));

foreach ( $contributor_ids as $contributor_id ) :
$post_count = count_user_posts( $contributor_id );
  // Move on if user has not published a post (yet).
  if ( ! $post_count ) {
    continue;
  }
?>

<div class="contributor">
  <div class="contributor-info">
    <div class="contributor-avatar"><?php echo get_avatar( $contributor_id, 132 ); ?></div>
    <div class="contributor-summary">
      <h2 class="contributor-name"><?php echo get_the_author_meta( 'display_name', $contributor_id ); ?></h2>
      <p class="contributor-bio">
        <?php echo get_the_author_meta( 'description', $contributor_id ); ?>
      </p>
      <a class="button contributor-posts-link" href="<?php echo esc_url( get_author_posts_url( $contributor_id ) ); ?>">
        <?php printf( _n( '%d Article', '%d Articles', $post_count, 'twentyfourteen' ), $post_count ); ?>
      </a>
    </div><!-- .contributor-summary -->
  </div><!-- .contributor-info -->
</div><!-- .contributor -->

<?php
endforeach;
?>

We will again add it below the call for the_content() with the following result:

The unstyled custom contributors page.38
The unstyled custom contributors page. (View large version39)

Now for a little bit of styling:

/* Contributor page */

.contributor {
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing:      border-box;
  display: inline-block;
  padding: 48px 10px;
}
.contributor p {
  margin-bottom: 1rem;
}
.contributor-info {
  margin: 0 auto 0 168px;
}
.contributor-avatar {
  border: 1px solid rgba(0, 0, 0, 0.1);
  float: left;
  line-height: 0;
  margin: 0 30px 0 -168px;
  padding: 2px;
}
.contributor-avatar img{
  border-radius: 0;
}
.contributor-summary {
  float: left;
}
.contributor-name{
  font-weight: normal;
  margin: 0 !important;
}
.contributor-posts-link {
  background-color: #24890d;
  border: 0 none;
  border-radius: 0;
  color: #fff;
  display: inline-block;
  font-size: 12px;
  font-weight: 700;
  line-height: normal;
  padding: 10px 30px 11px;
  text-transform: uppercase;
  vertical-align: bottom;
}
.contributor-posts-link:hover {
  color: #000;
  text-decoration: none;
}

And that should be it. Thanks Twenty Fourteen!

5. Customized Archive Page Link

Twenty Twelve comes with its own template for archive pages. It will jump into action, for example, when you attempt to view all past posts from a certain category.

However, I want something a little more like what Problogger40 has done: a page that lets people discover additional content on my site in several different ways. That, again, is done with a page template.

Staying with our mixed template from before, we will add the following below the the_content() call:

<div class="archive-search-form"><?php get_search_form(); ?></div>

<h2>Archives by Year:</h2>
<ul><?php wp_get_archives('type=yearly'); ?></ul>

<h2>Archives by Month:</h2>
<ul><?php wp_get_archives('type=monthly'); ?></ul>
   
<h2>Archives by Subject:</h2>
<ul> <?php wp_list_categories('title_li='); ?></ul>

Plus, a little bit of styling for the search bar:

.archive-search-form {
  padding: 10px 0;
  text-align: center;
}

And the result should look a little bit like this:

The custom archive page.41
The custom archive page. (View large version42)

For completion’s sake, here is the entire file:

<?php
/**
 * Template Name: Custom archive template
 *
 */

get_header(); ?>

<div id="primary" class="site-content">
  <div id="content" role="main">

    <?php while ( have_posts() ) : the_post(); ?>
         
      <header class="entry-header">
        <?php the_post_thumbnail(); ?>
        <h1 class="entry-title"><?php the_title(); ?></h1>
      </header>

      <div class="entry-content">
        <?php the_content(); ?>
      
        <div class="archive-search-form"><?php get_search_form(); ?></div>

        <h2>Archives by Year:</h2>
        <ul><?php wp_get_archives('type=yearly'); ?></ul>

        <h2>Archives by Month:</h2>
        <ul><?php wp_get_archives('type=monthly'); ?></ul>
                
        <h2>Archives by Subject:</h2>
        <ul><?php wp_list_categories('title_li='); ?></ul>
      </div><!-- #entry-content -->

      <?php comments_template( '', true ); ?>               
    <?php endwhile; // end of the loop. ?>             
  </div><!-- #content -->
</div><!-- #primary -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

Don’t forget to assign it to a page!

WordPress Page Templates In A Nutshell Link

On your way to mastering WordPress, learning to use page templates is an important step. They can make customizing your website very, very easy and allow you to assign unique functionality and design to as many or few pages as you wish. From adding widget areas to showing custom post types to displaying a list of your website’s contributors — the possibilities are practically endless.

Whether you use conditional tags, exploit the WordPress template hierarchy, or create page-specific template files is entirely up to you and what you are trying to achieve. Start off small and work your way up to more complicated things. It won’t be long before every part of your WordPress website will answer to your every call.

Do you have experience using page templates in WordPress? What other use cases can you add to the list? Any important details to add? Please tell us about it in the comments.

Image credit: Kevin Phillips43

(og, ml)

Footnotes Link

  1. 1 http://codex.wordpress.org
  2. 2 https://addons.mozilla.org/en-us/firefox/addon/firebug/
  3. 3 https://www.smashingmagazine.com/2014/08/a-better-404-page/
  4. 4 http://codex.wordpress.org/Template_Hierarchy#The_Template_Hierarchy_In_Detail
  5. 5 http://wphierarchy.com/
  6. 6 https://www.smashingmagazine.com/wp-content/uploads/2015/05/01-wp-template-hierarchy-opt.jpg
  7. 7 http://codex.wordpress.org/
  8. 8 https://www.smashingmagazine.com/wp-content/uploads/2015/05/01-wp-template-hierarchy-opt.jpg
  9. 9 http://codex.wordpress.org/Conditional_Tags
  10. 10 http://codex.wordpress.org/Conditional_Tags
  11. 11 http://www.themelab.com/ultimate-guide-wordpress-conditional-tags/
  12. 12 https://www.smashingmagazine.com/wp-content/uploads/2015/05/02-page-attributes-opt.jpg
  13. 13 https://www.smashingmagazine.com/wp-content/uploads/2015/05/02-page-attributes-opt.jpg
  14. 14 https://www.smashingmagazine.com/wp-content/uploads/2015/05/03-choose-page-template-manually-opt.jpg
  15. 15 https://www.smashingmagazine.com/wp-content/uploads/2015/05/03-choose-page-template-manually-opt.jpg
  16. 16 https://www.smashingmagazine.com/2012/06/create-responsive-mobile-first-wordpress-theme/
  17. 17 https://wordpress.org/plugins/what-the-file/
  18. 18 https://www.smashingmagazine.com/wp-content/uploads/2015/05/04-default-template-opt.jpg
  19. 19 https://www.smashingmagazine.com/wp-content/uploads/2015/05/04-default-template-opt.jpg
  20. 20 http://codex.wordpress.org/Page_Templates#Filenames
  21. 21 https://www.smashingmagazine.com/wp-content/uploads/2015/05/05-custom-wp-page-template-without-sidebar-opt.jpg
  22. 22 https://www.smashingmagazine.com/wp-content/uploads/2015/05/05-custom-wp-page-template-without-sidebar-opt.jpg
  23. 23 https://www.smashingmagazine.com/wp-content/uploads/2015/05/06-custom-full-width-wp-page-template-opt.jpg
  24. 24 https://www.smashingmagazine.com/wp-content/uploads/2015/05/06-custom-full-width-wp-page-template-opt.jpg
  25. 25 https://www.smashingmagazine.com/wp-content/uploads/2015/05/07-404-page-template-widgets-opt.jpg
  26. 26 https://www.smashingmagazine.com/wp-content/uploads/2015/05/07-404-page-template-widgets-opt.jpg
  27. 27 https://www.smashingmagazine.com/wp-content/uploads/2015/05/08-customized-404-error-page-via-template-opt.jpg
  28. 28 https://www.smashingmagazine.com/wp-content/uploads/2015/05/08-customized-404-error-page-via-template-opt.jpg
  29. 29 https://wordpress.org/plugins/types/
  30. 30 https://www.smashingmagazine.com/wp-content/uploads/2015/05/09-portfolio-page-without-custom-page-template-opt.jpg
  31. 31 https://www.smashingmagazine.com/wp-content/uploads/2015/05/09-portfolio-page-without-custom-page-template-opt.jpg
  32. 32 https://www.smashingmagazine.com/wp-content/uploads/2015/05/10-custom-portfolio-template-without-styling-opt.jpg
  33. 33 https://www.smashingmagazine.com/wp-content/uploads/2015/05/10-custom-portfolio-template-without-styling-opt.jpg
  34. 34 https://www.smashingmagazine.com/wp-content/uploads/2015/05/11-custom-portfolio-template-including-styling-opt.jpg
  35. 35 https://www.smashingmagazine.com/wp-content/uploads/2015/05/11-custom-portfolio-template-including-styling-opt.jpg
  36. 36 https://www.smashingmagazine.com/wp-content/uploads/2015/05/12-custom-contributor-page-opt.jpg
  37. 37 https://www.smashingmagazine.com/wp-content/uploads/2015/05/12-custom-contributor-page-opt.jpg
  38. 38 https://www.smashingmagazine.com/wp-content/uploads/2015/05/13-custom-contributor-page-without-styling-opt.jpg
  39. 39 https://www.smashingmagazine.com/wp-content/uploads/2015/05/13-custom-contributor-page-without-styling-opt.jpg
  40. 40 http://www.problogger.net/archives/
  41. 41 https://www.smashingmagazine.com/wp-content/uploads/2015/05/14-custom-archive-page-opt.jpg
  42. 42 https://www.smashingmagazine.com/wp-content/uploads/2015/05/14-custom-archive-page-opt.jpg
  43. 43 http://pixabay.com/en/users/kpgolfpro-27707/
SmashingConf New York

Hold on, Tiger! Thank you for reading the article. Did you know that we also publish printed books and run friendly conferences – crafted for pros like you? Like SmashingConf Barcelona, on October 25–26, with smart design patterns and front-end techniques.

↑ Back to top Tweet itShare on Facebook

Nick Schäferhoff is an entrepreneur, online marketer, and professional blogger from Germany. When not building websites, creating content or helping his clients improve their online business, he can most often be found at the gym, the dojo or traveling the world with his wife. You can get in touch with him via Twitter or through his website.

  1. 1

    Nathan Mckay

    June 19, 2015 3:06 pm

    This article doesn’t really offer me anything that I don’t already know, but I can so relate to the introduction. WordPress is exactly how I got started in web development. Sure I did some fooling around with front end code prior to encountering WordPress. But when I crossed paths with WordPress, I took the whole plunge into the web development world. WordPress truly is the gateway drug for web developers. And I am one of its “victims”. It just makes everything seem so easy when you get started. Then the next thing you know you are writing AJAX post back calls and switch loops. LOL

    1
    • 2

      Hey Nathan, thanks for the comment. Glad you can relate. I got into WordPress when I was bootstrapping my startup and needed a website without being able to pay anyone for it. The startup didn’t last but I haven’t kicked the WordPress habit. However, like you I am a willing victim. Cheers!

      9
  2. 3

    Hi, I’m Sue and I am WordPress user…thanks for the great knowledge fix. This definitely article is definitely going into my reference library.

    3
  3. 5

    Great article, but it would be nice if you added an example with navigation. Not just prev/next, but numbered pages. I think a lot of people are struggling with that when they are creating custom post types.
    Carry on my wayward son!

    0
    • 6

      Marjan, first off thanks for putting Kansas in my head. Secondly, are you talking about numbered pagination below the list for custom post types? That is something that your theme should handle. I know that Genesis has it out of the box. Otherwise this plugin might help: https://wordpress.org/plugins/wp-pagenavi/

      1
      • 7

        :) Yes, that’s what I’m talking about. I think in your examples you would get just older or newer links (or prev, next, I’m not sure.). I think numbering is much better way of doing that, And yes, I’m using that plugin. It would be nice just to make a quick example of it. I think there are some extra parameters in array for paging. For myself I know, when I started with custom post types, pagination was giving me quite a headache. Anyways, have a nice weekend. :)

        0
        • 8

          Yes, you can set an extra parameter in the array to limit the number of posts that will be displayed on the site. However, as far as I know you need to address numbered pagination in another function. You have a nice weekend, too!

          0
    • 9

      For pagination I use WordPress built-in function “paginate_links” (https://codex.wordpress.org/Function_Reference/paginate_links). This function has not failed me :)

      3
  4. 11

    Shawn McCarthy

    June 20, 2015 12:01 am

    Excellent tutorial and very well explained!

    Next stop, template parts :)

    1
  5. 13

    Jhon Jhonson

    June 20, 2015 11:23 am

    This is a very informative blog for me. I am very much benefited after reading this blog. Keep sharing.

    1
  6. 15

    Fantastic write-up! WordPress was my gateway. Learned a little CSS to modify some existing themes…2 years later I’m freelancing as a web developer. again, great article!

    0
    • 16

      I can so relate! My world exploded when somebody showed me Firebug and that I could do “live” changes to my WordPress website. Fast forward a few years and I’m making a living off of it. How great is that? Thanks for the thumbs up!

      1
  7. 17

    Great article – I could really relate to the intro but then it had so much information that I didn’t know! All stuff that you can get by without knowing but it’s good to know the how it really works under the hood.

    0
    • 18

      Hey Ted, thanks for the kind words. Thankfully with WordPress there is always more to learn. You can always push your skills a little further. And knowing custom templates is definitely an important step. Have fun implementing them!

      0
  8. 19

    omeiza owuda

    June 21, 2015 11:50 am

    This is a very educative article. WordPress has been playing an integral part in helping Web designers build a better Web product. I am most excited now that they have acquired Woo-commerce. we should all expect a better e-commerce system.

    1
    • 20

      Hi Omeiza, happy you like the article. And I agree, it will be exciting to see what is coming next for WordPress after the acquisition of WooCommerce. Cheers!

      -1
  9. 21

    This is great! Same here, as far as the intro goes! Wish I had it a few years ago.
    I find the the portfolio part especially helpful as I usually just grab someone else’s a hack away at it.

    Keep up the good work!

    0
  10. 23

    Thank you so much for this! I’ve done a bit with templates, but mostly just following tutorials that do not explain the “why” like you’ve done here. You’ve succeeded in writing clear instructions at a beginner / intermediate level which can be difficult for developers who’ve advanced beyond the basics. Well done.

    2
    • 24

      Hi Jodi and thank you! Yeah, sometimes it’s a lot more fun when you actually know what is happening behind the scenes that merely doing copy and paste. I’m happy to hear you got a lot out of the article. Hope you can put it to good use. Cheers!

      0
  11. 25

    People need to read more articles like this. It’s amazing how simple is WordPress theme development when you properly use what templates have to offer instead of practicing some strange kind of PHP sorcery. How many times I’ve seen that in a template written by somebody else? The rule of thumb is that PHP programmers write uglier code. Because actually you don’t have to be a programmer to write a wordpress template. Copypasting formulas from blogs and articles like this produce clearer code than using you senior-programmer-skills :3

    0
    • 26

      Klos, thanks for the comment! Copy and paste is definitely a good way to advance your WordPress knowledge. And I agree that beginners will find it easier to modify template files than using filters, actions and functions. Glad we agree!

      0
  12. 27

    Joomla Website Design

    June 24, 2015 10:35 am

    Thanx for the info abot the wordpress custom page, I am very intersted in this kind of blogs mainly realted to website design. Get to Know some necessary point about wordpress. Thanx for sharing :)

    0
  13. 29

    Cathy Goodwin

    June 25, 2015 3:38 pm

    I know just enough HTML/CSS to be dangerous! I like this guide because I’m going to need portfolio pages for a client, and I can give your code to my tech person. I try to help my clients avoid hidden charges from developers who swear they need a month and $5K when it’s just a few coding tweaks that take about 15 minutes. Thanks for de-mystifying some of those processes.

    0
  14. 31

    Great article Nick, thanks! I’m new to WordPress and currently learning to develop my own theme. For the past few days, I’ve been wondering if there is a way to keep page template files to a minimum while still having several unique pages for my theme. After reading your article, it seems like using custom page templates wins out over many conditional statements within one file. What advice do you have for planning how a site’s structure should dictate template file creation? In other words, planning it out when you’re still in the wire-framing stage.

    1
    • 32

      Hi Lee, sorry for the late reply. Congrats on working on your own theme! Custom page templates are definitely more flexible that conditional statements in my opinion, so I would go with that. As for the planning process: I like to keep things as simple as possible and templates to a minimum. That means I will try to come up with a default template that will apply to most pages and only introduce other templates for those pages that will need to be drastically altered in layout or design. Does that answer your question?

      0
      • 33

        That helps a lot, thanks! I created wireframes before learning how WordPress templates work and ended up with 11 different page layouts, some lightly similar, some not. Then I ran into having just as many different page-{slug name}.php files and it didn’t seem right.

        Now I know why it helps to have a understanding of WordPress templates when you’re in the sketching and idea phase of a web project. I have much to learn! Thanks again Nick.

        1
  15. 35

    Thanks for Sharing the Information..

    0
  16. 37

    I’m in the process of converting a static site to WordPress and wondered if my planned approach of using shortcodes to dynamically build a list of page content (from child pages to achieve this – 25sevencampersales.co.uk/vw-camper-vans-for-sale.htm) would be better than using defining those pages as posts and just loop through them to build my list?

    Great article by the way!

    0
    • 38

      Hey Richard, thanks I appreciate it!

      As for your question: In the end the right approach is what gives you the best end result and most control over your content. If you are satisfied with using shortcodes, go for it. I personally would think about using custom post types or an e-commerce solution. Also has the advantage that each of your items would have its own URL and could be listed within categories. Might be a good idea for SEO purposes.

      -1
  17. 39

    Nick this is a well written article. You truly know how to capture your audience during the introduction phase. I completely agree that once you try WordPress you’re hooked and never turn back. WordPress can be difficult to use without code or design experience, but its not impossible. I recently came across http://buildawpsite.com and found it extremely easy to customize a site using their drag and drop editing system. Check out this site, its definitely something that you should write about and share with your readers. Thanks again for touching upon this topic.

    0
  18. 41

    Thanks for the article! The big thing I learned here is being able to add a custom widget, like the 404 widget, and being able to set that up in the backend. The next time I work with WordPress I’m going to try it out that way, rather than coding directly in the 404.php file!

    I have set up a custom page template for my portfolio page of my site – what helped me was using a custom metabox plugin to set up some custom metaboxes on the backend, so that I could have pull fields I only needed for the portfolio into that page template. (I think this was the one I used: http://themefoundation.com/wordpress-meta-boxes-guide/ )

    0
    • 42

      Kim, thanks for the comment! Yeah, the dynamic 404 page was an eye opener for me too. Happy to hear you made your portfolio page work and thanks for letting everyone know about that plugin. Keep up the good work!

      0
  19. 43

    Bjarni Wark

    July 10, 2015 7:45 am

    Singular.php – A new theme template file for WordPress 4.3
    It will be a used to if a page.php or single.php is not present.

    0
  20. 45

    Your introduction of WordPress as a gateway to web design sums up my experience with it as well. Despite criticism, debates over PHP or developers advocating the use of other tools. One of the many WordPress advantages is exactly what you describe. Lowering the barrier to entry in a field is not a bad thing. If anything, writing my first WP theme gave me a new-found respect for actual developers.

    2

↑ Back to top