Yesterday, I sketched out how to conceptualize how many of us are likely used to working with WordPress templates.
To be clear, we can’t help but include template tags because that’s the nature of how WordPress and general PHP-based content management systems work.
The problem comes whenever we’re working with templates that contain code making more complex calls to various APIs. Though I demonstrated this using WP_Query (and will continue to do so), it’s not just that query.
Anyway, though, what are we supposed to do with this?
WordPress Templates: When HTML Calls PHP
First, it’s important to think about why mixing this much PHP and mark up is a bad idea.
It’s easy to say that it makes it harder to keep the code DRY (and there is truth to that), but what if we’re just going to be using a single query or a single block of code once? Is being DRY really that important then?
To be clear, yes, I think it’s important for the sake of keeping the code DRY, but if we’re only going to be using a call once I still think it matters if for no other reason than keeping the template code as clean as possible.
Think of it this way: Whenever we want to display the title, the content, and the post’s author, all we need to call are three functions:
So imagine adapting the following code (which is what we looked at in the previous post):
To look something like this:
Much cleaner, right? But there’s more to what you see than this. Specifically, if we’re going to be working with HTML behind-the-scenes, we need to make sure that we’re sanitizing it correctly using something like wp_kses:
Now, the idea of echo’ing HTML from PHP into a WordPress template is considered an anti-pattern by some developers. And this is not without merit.
There’s a balancing act to be played during the course of this series though: It’s a matter of introducing how people often present information and then cleaning it up a bit.
To take this a bit further, it’s possible – and not alltogether a bad idea – to separate the WP_Query function even more to use get_template_part. This carries with it a bit of cleaner code but also requires that we look at that function in-depth.
And that’s something that I’m not interested in doing in this particular series.
How Should We Visualize This?
When it comes to templating, we can conceptualize this in a couple of a different ways.
- In some templating languages, it’s helpful to think of the PHP injecting the information into the template,
- In the example above, it’s helpful to think of the template file requesting the information from the PHP script.
So in the above example, we have a function located in, say, functions.php and the template file calling into it:
Make sense? But how this is accomplished – in terms of the code behind that single function call – is content for a post all its own.
And that’s what I’ll be looking at in the following post.