Post Meta

Estimated reading: 2 minutes

Post Meta or custom fields has become an integrated part of WordPress. As such, Timber has made it incredibly easy to render custom fields.

Consider a site that has posts about a specific workout, for instance a running blog. The posts have custom fields:

  • Distance – how long your run was
  • Start Time – When you started the run
  • Finish Time – When you finish the run
  • Location – Where your run took place

We’re not going to explain how to add the custom fields. You can use frameworks like ACF or Meta Box for that, or any other framework for that matter. In this example our fieldnames reflect their purpose.

<div class="run-information">
    <li><strong>Distance:</strong>{{ post.meta( 'distance' ) }}</li>
    <li><strong>Start Time:</strong>{{ post.meta('start_time') }}</li>
    <li><strong>End Time:</strong>{{ post.meta('finish_time') }}</li>
    <li><strong>Location:</strong>{{ post.meta('location') }}</li>

This method works for post meta that is stored as a string. But with the increase of popular custom field frameworks, the storage of meta data may differ for more advanced fields, and return an array or object instead.

Using the framework methods with Toolbox

When post.meta doesn’t return a useful string, you might find comfort in the fact that you can use the methods provided by these frameworks quite easily.

Imagine having added an ACF Pro repeater field for a FAQ section on a post. Just a simple repeater in a field called ‘faq_questions‘ and two subfields ‘title‘ and ‘content‘. To list the questions we only need to do:

{% for question in tb.get_field( 'faq_questions' )  %}
  <h3>{{ question.title }}</h3>
  {{ question.content }}
{% endfor %}

Click here to learn more about the tb proxy class. Using tb we can call the ACF get_field method and get the field with the set return format on the field (if available).

Share this Doc

Post Meta

Or copy link