WordPress is an extremely popular and beloved web application that powers approximately one quarter of all websites. It’s a framework, a content management system (CMS), a blogging tool, a publishing platform—you name it, WordPress can do it. It’s become so popular because of its versatility, ease to set up, and active community.

Need help installing WordPress? Check out my colleague Tim’s step-by-step guide.

Its CMS capabilities are constantly updated and being reinvented, but the code “behind the curtains” doesn’t get as much love as us web developers would hope for. The procedural coding style it follows is easy to understand and familiarize yourself with, but sacrifices efficiency and reusability.

“Fast, practical, sustainable, and re-usable” are words that make web developers happy. No dev—or at least no sane dev—will opt for the complicated route when trying to solve a problem. When expectations and deadlines are set, it is up to you and your team to reach the finish line and deliver. Finding ways to develop practical code will remove a lot of headaches from your life, and will allow you to scale and maintain your projects with ease.

You’re reading this blog because you use, or want to use, WordPress in your next project and you’re interested in learning better ways to code. If you simply stumbled here and are interested in knowing more about the basics of WordPress and the reasons why it rocks, you might want to start by reading this other article we wrote that explains just that. Whether you’re a rookie or an experienced WordPress developer, the tools I am about to show you will make your life easier—no doubt about it.

 

WordPress, y u no easy to theme?

Like any other CMS out there, WordPress offers a complete backend straight out of the box. An available database and a quick installation will get you up and running in less than 15 minutes. So the real development starts on the “theme” level. In WordPress, a theme is not only the “skin” of your site, it’s also the structure of it. It controls the way your pages and templates work, how you want to show data, and how you want it to look.

WordPress could do a better job of keeping things tidy when it comes to themes. It does everything else right, but the way they tackle theming isn’t the best, specifically in terms of organization and efficiency. Everything is handled in the same PHP file. The fetching and parsing of data and the outputting into HTML is all intertwined. Working in this type of system makes it easy—and almost inevitable—to get to a point where your files are full of the much feared “spaghetti code” (code that’s messy, unreadable, and an instant nightmare to everyone who didn’t write it).

This is where Timber comes into play. Timber is a library that fixes everything that’s wrong with WordPress theming. It makes WordPress development a breeze, and even bulks it up with some cool new tools, such as the templating PHP language, Twig.

It’s going down, I’m yelling…

Timber was created by the folks at Upstatement in an effort to make WordPress development better. It’s made by developers, for developers. A website that uses Timber doesn’t look any different in a browser, but it’s drastically different inside, behind the scenes.

Timber takes practices like Object Oriented Programming and Model, Controller, View (MVC) Design and incorporates them into WordPress development. The utilities and practices Timber offers will make your code clean, organized, and reusable. You’ll be proud of the code you put out there and your peers will thank you for it. No more “spaghetti code.”

This is interesting, go on.

As mentioned before, Timber converts WordPress themes into an MVC pattern. The data portion of a page is fetched and parsed in the PHP file (controller), then passed to the display file (view), where it can be outputted as HTML. Let’s take a look:

This is the old way a single.php file would look:

single.php


get_header();
if (have_posts()) :
  while (have_posts()) :
     the_post();
        the_content();
  endwhile;
endif;
get_footer(); 

 

It’s not bad, but it takes multiple steps to do simple things. I don’t know all of the WordPress functions by heart. And it’s annoying to have to search their documentation for the function I need and for the parameters I have to pass through it. Precious time gets wasted.

This is how Timber handles it. The .php file preps data and then calls the .twig file, which takes care of making it look awesome.

single.php


if (class_exists('Timber')) {

   $context = Timber::get_context();
   $post = new TimberPost();
   $context['post'] = $post;

   // Render Template
   Timber::render('single.twig', $context);
}

 

Goodbye “WordPress Loop,” no one is gonna miss you.

Twig is the bee’s knees.

Even though this is a quick example, you can already see the difference that Timber and the Twig template engine bring. The .php files are meant to strictly handle complex logic that shapes your objects, and the .twig file is meant for simple looping and conditioning of data. That way you can divide your tasks when creating pages. First and foremost, make things work; then make them look good.

Other benefits of using Timber.

Simple theming: No more header and footer files that stitch your page via includes. The Twig templating library introduces the block tag, which can be inherited into other template files. This cool functionality will make the design of your HTML extremely easy and versatile.

Below is an example of what your base template would look like. It contains the definition of a block tag called “site_body”. In Twig, block tags are sections that serve as placeholders and as replacements. The one below is a placeholder.


<!DOCTYPE html>
<html id="html-container">

	<head>
		<title>Page Title</title>
        </head>

	<body itemscope itemtype="http://schema.org/WebPage">
   
             <header id="site-header" itemscope itemtype="http://schema.org/WPHeader">

             </header>

                   <section id="site-body" role="main">

                         {% block site_body %}

                               {# SITE BODY GOES HERE #}

                          {% endblock %}

		    </section>

              <footer id="site-footer" itemscope itemtype="http://schema.org/WPFooter">

              </footer>
       
	</body>
</html>

 

The single.twig file inherits the base.twig file and replaces the placeholder block tag with actual content. Mind blown.


{% extends 'base.twig' %}

{# SITE BODY #}
{% block site_body %}

       <div id="content">
           {{ post.content }}
       </div>

{% endblock %}

Timber in a nutshell.

As you can see, there are a lot of cool (and helpful) features that Timber brings to the table. It will make your code simple and intuitive, which will create “clear” development between you and your peers. Twig also comes with a robust set of features that you’ll love (check batch looping for example).

If you’ve been developing WordPress sites for a while and have settled in their old ways, don’t fear. Switching to the “Timber ways” will take a small learning curve, but you’ll reap the benefits almost instantly.

Give it a shot. Check out their docs and start building better WordPress sites.

Resources

Timber