Welcome to this lesson where we take a deep dive into the details of how WordPress loads templates in a browser.
With this lesson, you will:
- explain how WordPress uses the query string,
- briefly explain the template hierarchy diagram, and
- describe the template hierarchy for a given page being queried.
How does WordPress use the query string?
When someone visits a page on a WordPress site, the query string helps determine which template should be used according to some rules we’ll go over later in this lesson. To better understand the query string itself, let’s take a look at a simple example within the WordPress dashboard.
The plain permalink structure uses the query string with the question mark, parameter, and then the value being the page or post ID in the database. If we were to change the permalink structure from post name to plain and then save that change, let’s now take a look at a page that we actually have available. And we’ve got the sample page.
If we hover over the title here, we see the ID is 2 down in the bottom left hand corner. If we go into the front end, we can actually enter in the query string to see if the sample page will get pulled up for us. Here you put in a forward slash and then page ID equals 2 after the question mark and it did pull it up correctly.
WordPress database
Let’s now take a look at the database to see how WordPress handles the query string next. WordPress has a table called WP posts and a field called post type. Let’s take a look at the data.
We want the post with ID of 2. That was our sample page. So we’ll open that up and if we scroll down to the bottom, we’ll see the post type is page. This is how WordPress knows to now look for a page template.
Overview of the template hierarchy diagram
Available on WordPress.org is this diagram to help us better understand the rules that are being applied when WordPress is deciding which template to use for the page or post being visited by the end user.
We have in black the page types and then next in the peaches variable templates. Then we have in green secondary templates and the blue ones are your primary templates.
Query example
Let’s take a look at an example now for a given page being queried.
If we were to go to the main domain of a website, otherwise known as the front page, then WordPress will look for the front page.html template. If that’s not available, it will move on to the home.html template.
And then finally, if that’s not available, it will fall back on the ultimate fallback template which is your index.html template. This explains why index.html is a required file for your theme.
Next steps
To learn more about the template hierarchy, you can go to the theme handbook on WordPress.org.