As I was tired of seeing so many badly developed WordPress themes where the code was not sustainable, the understanding of it took a long time and moreover it was filled with procedural code that was not even organised properly, I was looking for a solution to separate the HTML code completely from the PHP one in a WordPress theme.
This has several advantages including:
– Your templates look cleaner and are easier to maintain by the front-end developers. No more messy PHP code within HTML tags!
– All the templates are organised in one location and updating them (even with a WYSIWYG editor) is much easier
– All the logic/parsing of the information, database fetching is done in the PHP code.
Besides using functions.php and other common files to store the PHP code, I strongly recommend using PHP classes to manage a theme. It can save you time and, again, you have everything kept into an organised place.
After some research, I found Timber, a WordPress plugin, that is becoming more and more popular, powered by a modern template engine for PHP, called Twig.
This fast, secure and flexible template engine is brought to you by Fabien Potencier, the creator of the Symfony framework. Twig is released under the new BSD license.
Back to Timber, I’d like to show you some examples of how the logic is separated from the presentation.
single.php
[php]
$context = Timber::get_context();
$context[‘foo’] = ‘Bar!’;
$context[‘post’] = new TimberPost();
Timber::render(‘single.twig’, $context);
[/php]
single.twig
[html]
{% extends "base.twig" %}
{% block content %}
<h1 class="big-title">{{foo}}</h1>
<h2>{{post.title}}</h2>
<img src="{{post.thumbnail.src}}" />
<div class="body">{{post.content}}</div>
{% endblock %}
[/html]
As you can see “post” is assigned to the template and from there its values are printed. Here’s another example of showing a featured image the old way:
[php]
<?php
$thumb_id = get_post_thumbnail_id($post->ID);
$url = wp_get_attachment_url($thumb_id);
?>
<img src="<?php echo $url; ?>" alt="Thumbnail for <?php echo $post->post_title; ?>" />
[/php]
To do the same in Twig, while looping through the posts, you can use only one line:
[html]<img src="{{post.thumbnail.src}}" alt="Thumbnail for Timber" />[/html]
Yes, MVC WordPress Theme development can be confusing in the beginning if you were used to code the old way, but trust me, once you get used to it and see how powerful it is, you will not go back to the old style again when developing WordPress themes and PHP projects in general.
Note that popular PHP frameworks are using the MVC approach for a reason. If WordPress doesn’t offer this by default, then why not implementing it ourselves?