How does WordPress load templates?

The short answer:

– go see https://codex.wordpress.org/Template_Hierarchy

However, here’s a worked-out example.

I have a page called News with the slug “news”.  Here’s how WordPress loads the necessary page:

1. Apache runs your root /index.php file

2. This require’s

3. wp-blog-header then:

require_once’s wp-load.php

runs wp() and

require_once’s template-loader.php

4. template-loader.php does a few checks and then runs a huge if, elseif:

Lovely!

It turns out that the example given sets $template to ‘wp-content/themes/<theme name>/page-news.php’.

How does it do that? Well, if we search for the function get_page_templates() it turns out there are 3 occurrences in the WordPress code (in wp-admin/includes/theme.php and in various wp-includes files – class-wp-theme.php, template.php).

So, which one is it using?

The answer:

wp-includes/template.php which returns the value here:

Where is get_page_template_slug() defined?

In wp-includes/post-template.php. This works out the post using the post_id.

Then it works out the template using get_post_meta() (which is defined in post.php).

get_post_meta simply returns the result of another function get_metadata which is defined in meta.php.

The full code:

In meta.php > get_metadata it checks $meta_key. It cycles through a bunch of values in $meta_cache until it gets to $meta_key = ‘_wp_mf_page_template’.

The code:

cycles through the $meta_cache values just to decide the template! I had 343 values!

I literally gave up here as, whilst I spotted a $meta_key = “_wp_page_template” it continued to cycle through the $meta_cache values. Without wasting more time on this I can only assume it found the value here.

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *