In the last post, we looked at getting a Twig generated WordPress theme up and running. I’ll soon begin looking at styling it with SASS and then getting it JavaScript dependencies loaded via Require.js, but first, I’d like to clean up the template code a little. See, last time we were doing something like this to get the posts:

Where “posts” was a php iterator that used the WordPress loop. We were also using a proxy class to access wordpress functions in the template. While this works, I wasn’t too happy with the situation in general. The template was making too many decisions and calling functions. Templates shouldn’t be heavy on logic, because their only purpose should be to display stuff, not to decide what gets displayed.

It also fails to address another problem that I find annoying in wordpress – the content tree is generated during the construction of the page, not before it. That means that certain information isn’t normally available while building the header, for example. In the past, I’ve used a workaround which involves multiple queries and resetting the loop, but this time, I wanted it built into the theme.

The solution is as simple as iterating through the loop completely before starting to render the templates. In this way, we can build up everything the template needs beforehand, so it does not need to make any additional calls. Data is accessible all through the template, and the template itself becomes much simpler. Here’s the part of index.php where we’re building up the content:

In the excerpt above, you can see that we’re pulling data in from wordpress itself, and adding some metadata of our own. For example,

'template' => $site->get_format()

tells the post which template file it should use, for example, content.html.twig, summary-gallery.html.twig, and so on. The template doesn’t need to make any decisions. We’re also taking the opportunity to make the fields consistent. In

We’re setting the post content to the value of content if we’re showing a single post, or the value of the summary if we’re showing a list of posts. Both the summary and the full post templates will receive a ‘content’ property that represents their primary content:

The only function I’m still calling directly is site.text, which wraps the wordpress __ function for text localization. This is intentional as I’m planning to replace it at a later stage. Most plugins and systems which are used to support localization depend scan the theme files for uses of that function, and wrapping it in this way can prevent them from working properly. I’ll probably make some sort of localization file for the theme which sets up the localized values, but it’s not something I’ll be looking at right now.