Enjoyable WordPress theming with Timber (and ACF)

I was thinking of doing an in-depth tutorial on Timber. A few days since I started a draft, CSS-Tricks published “Timber and Twig Reignited My Love for WordPress“, which is a great read. However, I decided to push some of it live because this plugin deserves more love.

I’ve built a lot of WordPress sites. Recently, it has become more tedious work for me. Not for their complexity —most of corporate sites are fairly straightforward—, but because of the amount of work you have to do in Spaghetti code.

This situation changed when I found two amazing plugins: ACF (Advanced Custom Fields) and of course, Timber.

ACF lets you define additional custom fields on posts and pages (or even custom post types), without having to mess around with weird admin code and functions.php. Seriously, go check it out, buy the PRO version.

On the other hand, Timber “helps you create fully-customized WordPress themes faster with more sustainable code. With Timber, you write your HTML using the Twig Template Engine separate from your PHP files.”

Getting started

Install Timber through the WordPress admin or by downloading it from GitHub.

That’s it! At this point you’re ready to use Timber. You can start using it right now with your current theme files.
However, if you’re starting from zero I strongly recommend using Timber’s Starter Theme.

Once you’re there, you’ll find all your PHP files on the root, and on /template folder all twig files, with .twig extension. That way, every bit of logic stays separated from the presentation.

The documentation on Timber, ACF and Twig is detailed and clear. So go check them out and start building cleaner, more maintainable websites!

Loop list in batches using Twig (or plain PHP)

Recently I had to loop through a series of elements in a WordPress template (thanks Timber), which happened to be using Bootstrap.

If you ever used Bootstrap, you are familiar with the following markup:

The problem here is very common. You have to:

  • Loop every 3/4/n items.
  • Insert a separator or whatever every 3/4/n items.

You can achieve this with modulo (divisibleby) and checking if the loop index is last and other weird magic. However, Twig introduced the batch filter in version 1.12.3, where you can make this much less cumbersome.

So, adapting the current example and their docs, this is how we achieve a clean loop:

Much better, right?

I realized PHP has a built-in function that handles this. It’s called array_chunk which, of course, splits an array into chunks (or batches as I recalled, and the reason why I hadn’t been able to find it on the docs.)

Edit 19 Jul: Added plain PHP version.