Creating and using a custom page template

WordPress allows you to create custom templates. These can only be used for pages (not for posts). A custom template allows you to display content differently and to easily use built-in WordPress functions within a template.

Just to give you a good example of what custom page templates are and how they can benefit your site (no matter what theme you're using), let's create a custom version of the archives template. This is also what we will use to create a custom archives page that should be much more useful to our readers than the standard one. The following screenshot shows what the ARCHIVES page looks like on my blog right now:

There are just a couple of small links in the sidebar that redirect visitors to a standard monthly archive. Of course, later on, when there are more posts on your site, there will be many more links shown (exactly one link for each month of your site's existence).

Now, as far as the idea of archives goes, I have to admit, somewhat reluctantly, that WordPress has never been good at this. One of the few problems with the platform as a web publishing solution is the fact that posts usually have very short life spans. Whenever you publish a post, it sits on the front page for a while, and then it vanishes in the archives, never to be seen again, irrespective of whether it's still relevant or not. In the end, it's really hard for a new visitor to find these old posts on your site.

One of the few chances you have of reviving those old posts is mastering the art of SEO, and driving some new traffic to your old posts through your SEO efforts alone (this the most popular solution). But luckily, it's not the only way to fix this issue. Again, custom page templates are an interesting remedy here.

In the preceding screenshot, you can see that the default version of the archives is just a sidebar widget with some links to individual months. The problem with such content organization is that it provides a rather bad user experience. Archives, in general, are not about listing everything in one place; they are about providing a hub where the visitor can go and find a specific piece of content. For example, think about how archives work in your local library. This is what you want to eventually have on your site as well. So, what we're going to do here is say no to the traditional archives template in WordPress and create a custom page template to handle archives manually. Then, we're going to link to this archive from one of the menus. Here's how to do it.

On our new archives page, we want to achieve the following things:

To do this, we need to create a template. The following demonstrates the steps that we'll take:

  1. Create the template file. Make a copy of page.php and give it a new name. I like to prepend all of my custom template files with tmpl_, so that they are sorted separately from all of the WordPress template files that I will create. I'll name this file tmpl_archives.php. In order for WordPress to be able to identify this file as a template file, we need to add a specially styled comment to the top of the page (just as we did with style.css). The comment needs to be formatted as follows:
      <?php
      /* Template Name: Blog Archives Custom */
      ?>

In the wp-admin panel, the template will be identified by this template name, so make sure the name signals to you what the template is used for.

  1. Add WordPress functions. This is a crucial part of the process, but thankfully not a complicated one at this stage. Look over your new template file and find the occurrence of this line:
      <?php get_template_part('content', 'page'); ?>
  1. Now, erase it and put the following code in its place:
      <?php get_template_part('content', 'tmpl_archives'); ?>

This is the result we're after; the middle part of your tmpl_archives.php file should now look like the following:

      <?php while (have_posts()) : the_post(); ?>
      <?php get_template_part( 'content', 'tmpl_archives' ); ?>
      <?php endwhile; // end of the loop. ?>
  1. Next, create a completely new file called content-tmpl_archives.php and add the following code:
      <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
        <header class="entry-header">
          <?php the_title('<h1 class="entry-title">', '</h1>'); ?>
        </header>

        <div class="entry-content">
          <?php the_content(); ?>

          <div style="float: left; width: 50%;">
            <h2>Categories</h2>
            <ul>
            <?php wp_list_categories('orderby=name&title_li='); ?>
            </ul>
          </div>
          <div style="float: left; width: 50%;">
            <h2>Tags</h2>
            <?php wp_tag_cloud('smallest=8&largest=20'); ?>
          </div>
          <div style="clear: both;"></div><! -  clears float  - >

          <?php
          $how_many_last_posts = 15;
          echo '<h2>Last '.$how_many_last_posts.' Posts</h2>';
          $my_query = new WP_Query('post_type=post&nopaging=1');
          if($my_query->have_posts()) {
            echo '<ul>';
            $counter = 1;
            while($my_query->have_posts() && 
              $counter<=$how_many_last_posts) 
            {
              $my_query->the_post();?>
              <li><a href="<?php the_permalink() ?>"
                rel="bookmark" title="Permanent Link to <?php
                the_title_attribute(); ?>"><?php the_title();
                ?></a></li>
              <?php
              $counter++;
            }
            echo '</ul>';
            wp_reset_postdata();
          }
          ?>

          <h2>By Month</h2>
            <p><?php wp_get_archives('type=monthly&
              format=custom&after= |'); 
            ?></p>
        </div>

        <footer class="entry-footer">
        </footer>
      </article><! -  #post-##  - >

The code includes some additional functionality for our new archives template. In fact, because we are creating a custom template, we can add any of the WordPress functions we discovered earlier in the chapter, as well as any other WordPress function in existence (see Chapter 13, Creating a Non-Blog Website Part Two – E-Commerce Websites and Custom Content Elements).

Here are some of the more interesting parts of the code, starting with the following:

<div style="float: left; width: 50%;">
  <h2>Categories</h2>
  <ul>
  <?php wp_list_categories('orderby=name'); ?>
  </ul>
</div>

It's about adding a complete list of categories that are present on the site. The div elements are responsible for displaying this block on the left-hand side and allowing the next block, tags, to be placed next to it (it's a more effective way of achieving such an effect than using HTML tables, because it's a more cross-device-friendly approach).

The next part of the code is the following:

<div style="float: left; width: 50%;">
  <h2>Tags</h2>
  <?php wp_tag_cloud('smallest=8&largest=20'); ?>
</div>
<div style="clear: both;"></div><! -  clears float  - >

It has a very similar purpose, only this time we're displaying the aforementioned tag cloud. The last div element visible here is meant to clear the float parameter used in the previous div elements.

Next, we have the part responsible for displaying the latest posts, as follows:

<?php
$how_many_last_posts = 15;
echo '<h2>Last '.$how_many_last_posts.' Posts</h2>'; 
$my_query = new WP_Query('post_type=post&nopaging=1');
if($my_query->have_posts()) {
  echo '<ul>';
  $counter = 1;
  while($my_query->have_posts() && $counter<=$how_many_last_posts) {
    $my_query->the_post();
    ?>
    <li><a href="<?php the_permalink() ?>" rel="bookmark"
      title="Permanent Link to <?php the_title_attribute();
      ?>"><?php the_title(); ?></a></li>
    <?php
    $counter++;
  }
  echo '</ul>';
  wp_reset_postdata();
}
?>

Currently, the code displays the 15 latest posts, but this can be adjusted if you just change the value of the $how_many_last_posts variable.

Finally, there's the block that displays a traditional monthly archive, where every month is represented as a standard link, as follows:

<h2>By Month</h2>
<p><?php wp_get_archives('type=monthly&format=custom&after=
  |'); ?></p>

At this point, you can save the file and proceed to the next step, which is to apply the template to a page.

Leave your HTML editor and log into your wp-admin. You need to create the page in which you want to use this template. In my case, I'll name my new page Archives, to make its purpose clear. While working on the page, switch to the Document tab and scroll down to the Page Attributes section. This is where you'll find the Template setting, as demonstrated in the following screenshot:

Change it from Default template to Blog Archives Custom and save the draft or publish it right away. Now, in order to see the page somewhere, you have to add it to one of the menus. We already covered menus in Chapter 4, Pages, Media, and Importing/Exporting Content, so I'm sure you can get it done quickly. Once you have this handled, you can return to the frontend of your website and click on the Archives page. However, because your site is not that content-heavy at this point, you won't get a staggering effect, but there'll still be a nice presentation of the most recent posts, as shown in the following screenshot:

There is no limit to the number of custom templates that you can make for your WordPress theme.

These versions of the tmpl_archives.php file and the content-tmpl_archives.php file are available in the code bundle for this chapter, inside a sub-directory called phase 5.