Template Files

Okay, we have looked at the styles.css file, the functions.php file and handling javascript files. So what about the pile of php files that also live in a theme? These are called templates.

They are called templates because these files determine how different types of content are rendered for the viewer. In essence, WordPress core and plugins use their logic of their code to produce functionality and to communicate with the database and produce output for display to users. It is the job of theme templates (in conjunction with other theme files) to structure this display.

In some ways the child theme template rules are fairly simple, but there are nuances.

First, the simple rule. If a php file exists in the child theme with the same name and in the same relative place in the directory structure then it will be used instead of the version from the parent theme.

You can also add new template files that will be used under certain circumstances according to rules of the WordPress Template hierarchy. We will take a look at this below.

Parts of a template file

Below is an example of a template file.

<?php
/**
 * The main template file
 *
 * This is the most generic template file in a WordPress theme
 * and one of the two required files for a theme (the other being style.css).
 * It is used to display a page when nothing more specific matches a query.
 * E.g., it puts together the home page when no home.php file exists.
 *
 * @link https://codex.wordpress.org/Template_Hierarchy
 *
 * @package WordPress
 * @subpackage Twenty_Seventeen
 * @since 1.0
 * @version 1.0
 */

get_header(); ?>

<div class="wrap">
   <?php if ( is_home() && ! is_front_page() ) : ?>
      <header class="page-header">
         <h1 class="page-title"><?php single_post_title(); ?></h1>
      </header>
   <?php else : ?>
   <header class="page-header">
      <h2 class="page-title"><?php _e( 'Posts', 'twentyseventeen' ); ?></h2>
   </header>
   <?php endif; ?>

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

         <?php
         if ( have_posts() ) :

            /* Start the Loop */
            while ( have_posts() ) : the_post();

               /*
                * Include the Post-Format-specific template for the content.
                * If you want to override this in a child theme, then include a file
                * called content-___.php (where ___ is the Post Format name) and that will be used instead.
                */
               get_template_part( 'template-parts/post/content', get_post_format() );

            endwhile;

            the_posts_pagination( array(
               'prev_text' => twentyseventeen_get_svg( array( 'icon' => 'arrow-left' ) ) . '<span class="screen-reader-text">' . __( 'Previous page', 'twentyseventeen' ) . '</span>',
               'next_text' => '<span class="screen-reader-text">' . __( 'Next page', 'twentyseventeen' ) . '</span>' . twentyseventeen_get_svg( array( 'icon' => 'arrow-right' ) ),
               'before_page_number' => '<span class="meta-nav screen-reader-text">' . __( 'Page', 'twentyseventeen' ) . ' </span>',
            ) );

         else :

            get_template_part( 'template-parts/post/content', 'none' );

         endif;
         ?>

      </main><!-- #main -->
   </div><!-- #primary -->
   <?php get_sidebar(); ?>
</div><!-- .wrap -->

<?php get_footer();

 

I think it’s good practice to head a child theme template file with a comment block outlining why you have put a replacement template file in place, much as the example above includes a comment block explaining what the template does.

Template files, will of course contain a mix of PHP/HTML necessary to render the HTML tags and attributes. You will see it above. Anything between <?php ?> tags is php, the rest is HTML. Notice that the php can be scattered throughout.

Tags (functions)

An important part of template files is what WordPress calls template tags. These are basically Wordpress functions that provide the stuff that is going to go on the page. They are functions that have been specifically written for inclusion into template files.

They may also reference additional templates. For example,  in most themes (including the example above) there is a template called header.php that provides the page header. In other template files the template tag get_header() can be used as an instruction to run and load the header.php file, run whatever actions/hooks are associated with this and insert it at that point along with whatever content it needs.

There is quite a variety of template tags that serve various purposes. A list can be found here. It is these template tags that actually get the stuff of WordPress on to the page.

The Loop

The loop is a special and common set of php and template tags that are used to process WordPress items, typically posts, pages or that sort of thing. It’s basic skeleton looks like this:

So we have an if statement: do we have anything to loop through (a bunch of posts for instance), if not let’s stop now. If we do have something we enter the while loop, while we still have posts we haven’t looped through yet we’ll get the post, display its content, then loop around to the next post.

Now this is a pretty simple example, but let’s look back up the page to our template example and see if we can spot the loop hiding in there. And we can, but wait there a couple of twists. There is a tag in there called get_template_part, that seems like something we should know about. We’ll look at that next. Also there is an else part to our if statement, that shouldn’t bother us any. We use one template part if we have content and another if we don’t.

Template parts

Well, um, template parts are parts of templates. The basic idea is twofold:

  • We take some stuff out of a template and move it to its own file
  • By moving some of the template detail to another file it simplifies reading and altering the overall template structure, and
  • The template part itself might lend itself to use in more than one template. For example, let’s say my template part displays a post title, a post image, and the post excerpt. I may find that useful inside of loops in my blog listing template, archive templates and category templates.

So, if I want to tinker with fine details I can head into a template part and change it once for many uses and it simplifies my work in the larger page template structures. And before you ask, yes you can nest template parts inside of template parts. Here’s the developer doc on the template part call.

Template hierarchy

So, there are a bunch of different templates in most themes, how does WordPress know which template to use?

Let’s ask a different but related question: how do I display one page differently that the rest of the pages?

This is where a good knowledge of the template hierarchy is important. The basic principle of the hierarchy is that for each type of WordPress content the hierarchy will first look for the most specific template possible if it exists (likely a template for the specific individual item) and follow the hierarchy, getting more and more general, until it finds a template that will handle the content.

Have a look at this diagram of the WordPress template hierarchy. Let’s follow a simple stream to see how this works.

  1. Starting in the left column we’ll select a Page type. Let’s follow the Site Front page stream, it provides an example of medium complexity that includes most of the types of options.
  2.  For the Site Front Page WordPress will follow the diagram from left to right, first looking for a template called front-page.php. If it finds it, then it uses it. If it doesn’t it moves to step 3.
  3. Next it checks whether a static page or a blog-style posts page has been chosen in the site settings. If a static page has been selected then it shunts to the Page Template in the Singular Page Stream above. If posts has been chosen then we move to the right, let’s follow this trail.
  4. WordPress is now looking for a home.php template file. If it finds it, it uses it. If not we move to the next step.
  5. Finally we get to the index.php file which is used as a catchall for any content not having a more specific template.

So how do we use this? Let’s say I have a single page that I want a unique presentation for, different from all the other pages. I’ll follow the template hierarchy to see how I might do this.

  1. Starting on the left in the Singular Page row I’ll move to the right. First I get a decision, are we talking about a Single Post or a Single page, in this case it is page so I will drop to the bottom route.
  2. I move to the right from Static Page to Page Template and then I see I have another choice between Custom Template and Default Template. The Custom Template is for something called a Custom Post Type, my page is a regular page so I can follow along from Default Template.
  3. Skipping ahead and looking at the path, I see that if I do nothing else that WordPress will try first for a page.php file, failing that a singular.php file and finally failing that it will use index.php. Before that though there are two red boxes that might have a solution for me.
  4. I see that there is provision for page-$slug.php and page-$id.php. Without prattling on for too long, if it’s not too late already, each WordPress page has an $id number which is friendly to the database and it also has a page slug which is friendly to people and which I recognize from the page editing dialog box as providing the url. Also I can set/change page slugs.
  5. So, I will use the page slug method for my page. So, let’s say that my page slug is: dumb_boring_crap, then what I can do is create a file called page-dumb_boring_crap.php in my child theme and WordPress will use it as the template for this single page. What I’m more likely to do is save a copy of the page.php with this new name and alter it, because that will be much easier, most of the work will be done already.

Challenge #4: Add or Alter a template file

Okay, here the aim is to either add or alter a template file. This challenge is a little trickier to provide a set of specific steps for as each theme is a little different. However, the goal is to read a template file and determine how you can achieve your goals. As before, you can strike out on your own or try to follow the vague and general directions below.

The set challenge is something very common, we are not happy with the layout of our static home page and we want to alter it. This probably means adding a front-page.php file if there isn’t one in the theme already and altering it if there is one.

  1. Get to know the file hierarchy of the theme. Follow through the template hierarchy flowchart linked above for your theme to understand how various parts of the site are rendered. (Skip to the Some final gifts section below and install the What the File (WTF) plugin if you are seeking greater certainty.
  2. If you do not have a front-page.php template then you will need to create one. No, not from scratch, the plan here is to figure out which template is responsible for not giving you exactly what you want and copying it to front-page.php.
  3. Read and work your way through the file until you are pretty confident that you understand how it works.
  4. If you encounter the command get_template_part review the template part file as well. (As an example, my command is: get_template_part( 'content', get_post_format() ) I will be looking for the first item inside the bracket in quotes, in this case content. That means that I’m also going to review the content.php file.
  5. Also be on the look out for get_header, get_sidebar, and get_footer commands. These will use header.php, sidebar.php and footer.php respectively. You may want to review these if you want to do something in these areas.
  6. Formulate a plan of attack (include not only page template thinking, but potential css that may be involved as well). Let’s say that I want to remove the sidebar and footer from my front-page.php. Perhaps removing the get_sidebar and get_footer statements will do the trick.
  7. Try your plan out, but always build an escape route (make a copy of the file, use version control, etc).

Some final gifts

Before we look at resources and wrap up,  I want to lay down a scenario that I found myself in. I was working in a very complex WordPress environment, Commons in a Box based, which is built on top of Buddypress. I was using the Commons in a Box theme which is built on top of the Infinity Theme Engine. And I was trying to write a custom template part to replace one on the page.

So I pulled out my trusty dusty Template Hierarchy diagram and stared at it and then stared at the theme/child theme files. After about an hour of looking back and forth my brain began to hurt. All I wanted to know was which templates and template parts were building the damn page I was trying to alter.

Then I found the emotionally aptly named What the File (WTF) plugin. It puts a drop down in your admin bar that lists all templates and template parts involved in a given page. It now gets installed right after I activate a child theme.

Also, there are too other plugins (well one is a set of plugins) that are useful for development.

WP Inspect puts visual indicators on the rendered WordPress page signifying which hooks (actions and filters) were used to build the item.

Developer is a plugin which you can use to install one or more in a set of WordPress plugins of use to developers. There is a dizzying array, I suggest you go slowly and install one at a time with these.

Okay, one more. The last time (about a year ago) I installed the pile of stuff from the Developer plugin it made my head spin. Only tequila could settle my brain. Then I found Query Monitor. It does a smaller set of stuff, but it was exactly what I needed.