WordPress Template Hierarchy System

template hierarchy system

WordPress is built on themes and inside the themes are templates. The WordPress template hierarchy is a system to determine which templates are used to create what is displayed in the viewport. Different parts of the page are in different files, the header, the footer, the navigation, the content. A user clicks a link or enters a web address. This is a query. The query string determines which templates to call. The templates are called in hierarchical order. WordPress searches through the templates in the current theme’s directory and chooses the first matching template.

template hierarchy system – order

WordPress looks at the query and asks is this an archive page, singular page, site front page, blog post index page, error page or search page. Then it follows the hierarchy and asks if it is a single post page, or a static page. Are we using a custom template, or a default template is the next decision to make for WordPress. If WordPress can’t find a match it will default to index.php. A link can have an ID, which is a number, like a primary key in a table or address pointing to the content. It could have a slug instead, which is a more human friendly name that points to the content. That would be like about, or contact. WordPress looks for template files in this order: page template, page with slug , page with id, page.php, singular.php, then index.php.

template hierarchy system - file naming conventions

When naming a file, it is best to choose a name that describes the file’s content. So oscar.php should not be about Goldilocks. It is best to name files so that the next person looking for pieces of code can easily find the right file. WordPress says to use lowercase file, folder, and directory names. Camel case is not recommended. Underscores are ok if it is theme_1, theme_2, etc. if there are multiple words in a file name it is recommended to use a dash between them.

Summary

WordPress uses this system to retrieve the parts of the page needed to display the page in the viewport. It goes through the theme looking for the parts and then assembles them in an ordered way on the page.