Timber Post != WP Post

Estimated reading: 3 minutes

Next thing to mention is that Timber is built on top of the Twig Template Engine. It extends it and fills certain gaps that WordPress has. There’s a very important difference between a WP Post Object and a Timber Post Object. A Timber Post Object is a heavily extended version of the WP Post Object.

What does that mean?

In normal PHP with WordPress, within a Query Loop one or more Post Objects are returned. You typically have access to things like

<?php

// examples of properties available on the WP_Post object
$post->ID
$post->post_title
$post->post_content
$post->post_excerpt
$post->post_status
$post->post_name
$post->post_date
$post->post_modified
...

There’s a few more, but these are the ones you would typically use most often. The ID is needed for additional calls, to get the featured image for instance.

No more additional calls

Doing all these additional calls each and every time you need something is tedious. Why is all that data, which clearly belongs to that same post ID, so hard to get to? With Timber it isn’t anymore.

Timber does the calls for you, and makes sure to return what you need. You can get the thumbnail, terms, preview and much more on the TimberPost Object directly.

An example

Whenever you add the Timber Posts Module to a single post layout, the template will have access to something called a context. The context is simply the set of variables and globals the template has access to. By default the module gets the WP post or archive posts it is meant to render and adds that to the context. So, to render the title and content of the post we can use:

<h3>{{ post.title }}</h3>
{{ post.content }}

Within the Timber Posts module, the context’s ‘post’ variable is a Timber Post Object, which has additional properties, like ‘title’ and ‘content’. We could have used post.post_title and post.post_content as well.

This of course isn’t much, but to add the featured image is as easy as it gets:

<img src="{{ post.thumbnail.src }}" width="{{ post.thumbnail.width }}" height="{{ post.thumbnail.height }}" alt="{{ post.thumbnail.alt }}">
<h3>{{ post.title }}</h3>
{{ post.content }}

Here we’ve used the post.thumbnail property, something added by Timber. It gets the featured image url, its metadata and gives you access to them without having to do additional calls.

Adding the terms is just as easy:

<img src="{{ post.thumbnail.src }}" width="{{ post.thumbnail.width }}" height="{{ post.thumbnail.height }}" alt="{{ post.thumbnail.alt }}">
<div>{{ post.terms( 'category' )|join( ', ' ) }}</div>
<h3>{{ post.title }}</h3>
{{ post.content }}

The post.terms method allows you to get the category terms easily. Using a filter it then joins them using a comma and space delimiter.

Share this Doc

Timber Post != WP Post

Or copy link

CONTENTS