This is Part 2 of a series of posts that try to answer the question:
What are some good resources for someone who wanted to learn more about WordPress theme development?
I encourage you to checkout Part 1 in this series if you have not yet: Theme Developer’s Toolkit: Part 1.
In Part II we will be discussing a tool that every WordPress Theme Developer will find super handy.
Tool: The WordPress Template Hierarchy
A WordPress theme consists of a number of templates. They are reusable on a number of pages and posts. For example, the template page.php is the template that most of a site’s pages will use. The slightly less obviously named single.php is the template that all our blog posts will use.
A template will provide the types of content featured and layout of that content. A template is powerful and reusable though because the content will change for each page using that template.
So for example, let’s say the page.php template might layout all pages to have its title at the top and centered. Below that title the template might be built to show copy on the left and one featured image on the right.
If we wanted the About page to be a completely different layout than the page.php template we described before, we would need to build a new template. Let’s say in this template we built a special layout to display our awesome team and a hero image with our mission statement on it. In order for WordPress to know to use our new, special About page template and not the page.php template described before we would need to utilize the WordPress Template Hierarchy.
The people at WPSHOUT are apparently brilliant and turned this tool into a website that can be found here: https://wphierarchy.com/.
The WordPress template hierarchy is a tool that demonstrates how WordPress selects which template to use. Near the right hand side of the tool we see a purple box that read page.php. If we trace the line out of page.php two boxes over to the left we see a box that reads “page-$slug.php”. We can ignore the $ here, and focus on the word slug.
In our example, we want a custom template for the About page. If the About page were found at the URL www.example.com/about, than our slug would be “about”. It is the last part of the URL.
So in our theme we would create a file called page-about.php. In this file we could build our special About page template. When loading the About page of the site WordPress would use page-about.php instead of page.php. When viewing the Privacy Page noted earlier WordPress would continue to use the page.php template.
The WordPress Template Hierarchy is a powerful tool for learning how to build WordPress themes. It is also a great reference years into theme development.
If you enjoyed this post please checkout the next installment, Theme Developer’s Toolkit: Part 3.