Timber Logo

You are reading the documentation for Timber v2.x. Switch to the documentation for Timber v1.x.

Timber\​Post

This is the object you use to access or extend WordPress posts. Think of it as Timber's (more accessible) version of WP_Post. This is used throughout Timber to represent posts retrieved from WordPress making them available to Twig templates. See the PHP and Twig examples for an example of what it’s like to work with this object in your code.

single.php

PHP

$context = Timber::context();

Timber::render( 'single.twig', $context );

single.twig

Twig

<article>
<h1 class="headline">{{ post.title }}</h1>
<div class="body">
{{ post.content }}
</div>
</article>

HTML

<article>
<h1 class="headline">The Empire Strikes Back</h1>
<div class="body">
It is a dark time for the Rebellion. Although the Death Star has been
destroyed, Imperial troops have driven the Rebel forces from their
hidden base and pursued them across the galaxy.
</div>
</article>

Overview #

This class extends Timber\CoreEntity
This class implements Timber\DatedInterface, Timber\Setupable

Properties #

NameTypeDescription
$idintThe numeric WordPress id of a post.
$IDintThe numeric WordPress id of a post, capitalized to match WordPress usage.
$post_authorintThe numeric ID of the a post's author corresponding to the wp_user database table
$post_contentstringThe raw text of a WP post as stored in the database
$post_datestringThe raw date string as stored in the WP database, ex: 2014-07-05 18:01:39
$post_excerptstringThe raw text of a manual post excerpt as stored in the database
$post_parentintThe numeric ID of a post's parent post
$post_statusstringThe status of a post ("draft", "publish", etc.)
$post_titlestringThe raw text of a post's title as stored in the database
$post_typestringThe name of the post type, this is the machine name (so "my_custom_post_type" as opposed to "My Custom Post Type")
$slugstringThe URL-safe slug, this corresponds to the poorly-named "post_name" in the WP database, ex: "hello-world"

Methods #

NameReturn TypeSummary/Returns
__call()mixedThis is helpful for twig to return properties and methods see: https://github.com/fabpot/Twig/issues/2
__get()mixedThis is helpful for twig to return properties and methods see: https://github.com/fabpot/Twig/issues/2
__toString()stringOutputs the title of the post if you do something like <h1>{{post}}</h1>
author()\Timber\User or nullReturn the author of a post

Returns: A User object if found, false if not
authors()arrayGot more than one author? That's cool, but you'll need Co-Authors plus or another plugin to access any data
can_edit()boolChecks whether the current user can edit the post.
categories()arrayGet the categories on a particular post

Returns: of Timber\Term objects
category()\Timber\Term or nullGets a category attached to a post.
children()\Timber\PostCollectionInterfaceReturns an array of children on the post as Timber\Posts (or other claass as you define).
comment_count()intGets the number of comments on a post.

Returns: The number of comments on a post
comment_form()stringGets the comment form for use on a single article page

Returns: of HTML for the form
comments()bool or \Timber\CommentThreadGets the comments on a Timber\Post and returns them as an array of Timber\Comment objects (or whatever comment class you set).
content()stringGets the actual content of a WordPress post.
convert()Finds any WP_Post objects and converts them to Timber\Post objects.
date()stringGets the publishing date of the post.
edit_link()string or nullGets the edit link for a post if the current user has the correct rights.

Returns: The edit URL of a post in the WordPress admin or null if the current user can’t edit the post.
excerpt()\Timber\PostExcerptGets a excerpt of your post.
field_object()mixedGets the field object data from Advanced Custom Fields.
format()mixed
gallery()arrayReturns galleries from the post’s content.

Returns: A list of arrays, each containing gallery data and srcs parsed from the expanded shortcode.
get_field()mixedGets a post meta value.

Returns: The meta field value.
has_field()bool
has_term()bool
import_field()Import field data onto this object
link()stringget the permalink for a post object

Returns: ex: http://example.org/2015/07/my-awesome-post
modified_author()\Timber\User or nullGet the author (WordPress user) who last modified the post

Returns: A User object if found, false if not
modified_date()stringGets the date the post was last modified.
modified_time()stringGets the time of the last modification of the post to use in your template.
modified_timestamp()false or intGets the timestamp when the post was last modified.

Returns: Unix timestamp on success, false on failure.
name()string
next()mixedGets the next post that is adjacent to the current post in a collection.
pagination()arrayGets a data array to display a pagination for your paginated post.

Returns: An array with data to build your paginated content.
parent()bool or \Timber\PostGets the parent (if one exists) from a post as a Timber\Post object.
password_required()boolwhether post requires password and correct password has been provided
path()stringGets the relative path of a WP Post, so while link() will return http://example.org/2015/07/my-cool-post this will return just /2015/07/my-cool-post
prev()mixedGet the previous post that is adjacent to the current post in a collection.
preview()\Timber\PostExcerptGets an excerpt of your post.
setup()\Timber\PostSets up a post.

Returns: The post instance.
tags()arrayGets the tags on a post, uses WP's post_tag taxonomy
teardown()\Timber\PostResets variables after post has been used.

Returns: The post instance.
terms()arrayGets the terms associated with the post.

Returns: An array of taxonomies.
thumbnail()\Timber\Image or nullget the featured image as a Timber/Image

Returns: of your thumbnail
thumbnail_id()false or intGets the post’s thumbnail ID.

Returns: The default post’s ID. False if no thumbnail was defined.
time()stringGets the time the post was published to use in your template.
timestamp()false or intGets the timestamp when the post was published.

Returns: Unix timestamp on success, false on failure.
title()stringReturns the processed title to be used in templates. This returns the title of the post after WP's filters have run. This is analogous to the_title() in standard WP template tags.
type()\Timber\PostTypeReturns the PostType object for a post’s post type with labels and other info.

Class Methods #

__get() #

This is helpful for twig to return properties and methods see: https://github.com/fabpot/Twig/issues/2

This is also here to ensure that {{ post.class }} remains usable.

__get( mixed $field )

Returns: mixed


__call() #

This is helpful for twig to return properties and methods see: https://github.com/fabpot/Twig/issues/2

This is also here to ensure that {{ post.class }} remains usable

__call( mixed $field, mixed $args )

Returns: mixed


setup() #

Sets up a post.

Sets up the $post global, and other global variables as well as variables in the $wp_query global that makes Timber more compatible with WordPress.

This function will be called automatically when you loop over Timber posts as well as in Timber::context().

since 2.0.0

Returns: \Timber\Post The post instance.


teardown() #

Resets variables after post has been used.

This function will be called automatically when you loop over Timber posts.

since 2.0.0

Returns: \Timber\Post The post instance.


__toString() #

Outputs the title of the post if you do something like <h1>{{post}}</h1>

Returns: string


excerpt() #

Gets a excerpt of your post.

If you have an excerpt is set on the post, the excerpt will be used. Otherwise it will try to pull from an excerpt from post_content. If there’s a <!-- more --> tag in the post content, it will use that to mark where to pull through.

see Timber\PostExcerpt

excerpt( array $options = [] )

Returns: \Timber\PostExcerpt

NameTypeDescription
$optionsarrayAn array of configuration options for generating the excerpt. Default empty.

  • $words
    int Number of words in the excerpt. Default 50.
  • $chars
    int or bool Number of characters in the excerpt. Default false (no character limit).
  • $end
    string String to append to the end of the excerpt. Default '…' (HTML ellipsis character).
  • $force
    bool Whether to shorten the excerpt to the length/word count specified, if the editor wrote a manual excerpt longer than the set length. Default false.
  • $strip
    bool Whether to strip HTML tags. Default true.
  • $read_more
    string String for what the "Read More" text should be. Default 'Read More'.

Twig

<h2>{{ post.title }}</h2>
<div>{{ post.excerpt({ words: 100, read_more: 'Keep reading' }) }}</div>

preview() #

Gets an excerpt of your post.

DEPRECATED since 2.0.0, use {{ post.excerpt }} instead.

If you have an excerpt is set on the post, the excerpt will be used. Otherwise it will try to pull from an excerpt from post_content. If there’s a <!-- more --> tag in the post content, it will use that to mark where to pull through.

This method returns a Timber\PostExcerpt object, which is a chainable object. This means that you can change the output of the excerpt by adding more methods. Refer to the documentation of the Timber\PostExcerpt class to get an overview of all the available methods.

see Timber\PostExcerpt

Returns: \Timber\PostExcerpt

Twig

{# Use default excerpt #}
<p>{{ post.excerpt }}</p>

{# Change the post excerpt text #}
<p>{{ post.excerpt.read_more('Continue Reading') }}</p>

{# Additionally restrict the length to 50 words #}
<p>{{ post.excerpt.length(50).read_more('Continue Reading') }}</p>

comment_form() #

Gets the comment form for use on a single article page

comment_form( array $args = [] )

Returns: string of HTML for the form

NameTypeDescription
$argsarraysee WordPress docs on comment_form for reference on acceptable parameters

terms() #

Gets the terms associated with the post.

terms( string|array $query_args = [], array $options = [] )

Returns: array An array of taxonomies.

NameTypeDescription
$query_argsstring or arrayAny array of term query parameters for getting the terms. See WP_Term_Query::__construct() for supported arguments. Use the taxonomy argument to choose which taxonomies to get. Defaults to querying all registered taxonomies for the post type. You can use custom or built-in WordPress taxonomies (category, tag). Timber plays nice and figures out that tag, tags or post_tag are all the same (also for categories or category). For custom taxonomies you need to define the proper name.
$optionsarrayOptional. An array of options for the function.

  • $merge
    bool Whether the resulting array should be one big one (true) or whether it should be an array of sub-arrays for each taxonomy (false). Default true.

Twig

<section id="job-feed">
{% for post in job %}
<div class="job">
<h2>{{ post.title }}</h2>
<p>{{ post.terms({
taxonomy: 'category',
orderby: 'name',
order: 'ASC'
})|join(', ') }}
</p>
</div>
{% endfor %}
</section>

HTML

<section id="job-feed">
<div class="job">
<h2>Cheese Maker</h2>
<p>Cheese, Food, Fromage</p>
</div>
<div class="job">
<h2>Mime</h2>
<p>Performance, Silence</p>
</div>
</section>

PHP

// Get all terms of a taxonomy.
$terms = $post->terms( 'category' );

// Get terms of multiple taxonomies.
$terms = $post->terms( array( 'books', 'movies' ) );

// Use custom arguments for taxonomy query and options.
$terms = $post->terms( [
'taxonomy' => 'custom_tax',
'orderby' => 'count'
], [
'merge' => false
] );

has_term() #

has_term( string|int $term_name_or_id, string $taxonomy = 'all' )

Returns: bool

NameTypeDescription
$term_name_or_idstring or int
$taxonomystring

comment_count() #

Gets the number of comments on a post.

Returns: int The number of comments on a post


has_field() #

has_field( string $field_name )

Returns: bool

NameTypeDescription
$field_namestring

field_object() #

Gets the field object data from Advanced Custom Fields.

This includes metadata on the field like whether it's conditional or not.

since 1.6.0

field_object( string $field_name )

Returns: mixed

NameTypeDescription
$field_namestringof the field you want to lookup.

get_field() #

Gets a post meta value.

DEPRECATED since 2.0.0, use {{ post.meta('field_name') }} instead.

see Timber\Post::meta()

get_field( string $field_name = null )

Returns: mixed The meta field value.

NameTypeDescription
$field_namestringThe field name for which you want to get the value.

import_field() #

Import field data onto this object

DEPRECATED since since 2.0.0

import_field( string $field_name )

NameTypeDescription
$field_namestring

author() #

Return the author of a post

Returns: \Timber\User|null A User object if found, false if not

Twig

<h1>{{post.title}}</h1>
<p class="byline">
<a href="{{post.author.link}}">{{post.author.name}}</a>
</p>

authors() #

Got more than one author? That's cool, but you'll need Co-Authors plus or another plugin to access any data

Returns: array


modified_author() #

Get the author (WordPress user) who last modified the post

Returns: \Timber\User|null A User object if found, false if not

Twig

Last updated by {{ post.modified_author.name }}

HTML

Last updated by Harper Lee

categories() #

Get the categories on a particular post

Returns: array of Timber\Term objects


category() #

Gets a category attached to a post.

If multiple categories are set, it will return just the first one.

Returns: \Timber\Term|null


children() #

Returns an array of children on the post as Timber\Posts (or other claass as you define).

children( string|array $args = 'any' )

Returns: \Timber\PostCollectionInterface

NameTypeDescription
$argsstring or arrayoptional An array of arguments for the get_children function or a string/non-indexed array to use as the post type(s).

Twig

{% if post.children %}
Here are the child pages:
{% for child in post.children %}
<a href="{{ child.link }}">{{ child.title }}</a>
{% endfor %}
{% endif %}

comments() #

Gets the comments on a Timber\Post and returns them as an array of Timber\Comment objects (or whatever comment class you set).

see Timber\CommentThread for an example with nested comments

comments( int $count = null, string $order = 'wp', string $type = 'comment', string $status = 'approve' )

Returns: bool|\Timber\CommentThread

NameTypeDescription
$countintSet the number of comments you want to get. 0 is analogous to "all".
$orderstringUse ordering set in WordPress admin, or a different scheme.
$typestringFor when other plugins use the comments table for their own special purposes. Might be set to 'liveblog' or other, depending on what’s stored in your comments table.
$statusstringCould be 'pending', etc.

single.twig

Twig

<div id="post-comments">
<h4>Comments on {{ post.title }}</h4>
<ul>
{% for comment in post.comments() %}
{% include 'comment.twig' %}
{% endfor %}
</ul>
<div class="comment-form">
{{ function('comment_form') }}
</div>
</div>

comment.twig

Twig

{# comment.twig #}
<li>
<p class="comment-author">{{ comment.author.name }} says:</p>
<div>{{ comment.content }}</div>
</li>

content() #

Gets the actual content of a WordPress post.

As opposed to using {{ post.post_content }}, this will run the hooks/filters attached to the the_content filter. It will return your post’s content with WordPress filters run on it – which means it will parse blocks, convert shortcodes or run wpautop() on the content.

If you use page breaks in your content to split your post content into multiple pages, use {{ post.paged_content }} to display only the content for the current page.

content( int $page = '', mixed $len = -1 )

Returns: string

NameTypeDescription
$pageintOptional. The page to show if the content of the post is split into multiple pages. Read more about this in the Pagination Guide. Default 0.

Twig

<article>
<h1>{{ post.title }}</h1>

<div class="content">{{ post.content }}</div>
</article>

timestamp() #

Gets the timestamp when the post was published.

since 2.0.0

Returns: false|int Unix timestamp on success, false on failure.


modified_timestamp() #

Gets the timestamp when the post was last modified.

since 2.0.0

Returns: false|int Unix timestamp on success, false on failure.


date() #

Gets the publishing date of the post.

This function will also apply the get_the_date filter to the output.

If you use {{ post.date }} with the |time_ago filter, then make sure that you use a time format including the full time and not just the date.

date( string|null $date_format = null )

Returns: string

NameTypeDescription
$date_formatstring or nullOptional. PHP date format. Will use the date_format option as a default.

Twig

{# Uses date format set in Settings → General #}
Published on {{ post.date }}
OR
Published on {{ post.date('F jS') }}
which was
{{ post.date('U')|time_ago }}
{{ post.date('Y-m-d H:i:s')|time_ago }}
{{ post.date(constant('DATE_ATOM'))|time_ago }}

HTML

Published on January 12, 2015
OR
Published on Jan 12th
which was
8 years ago

modified_date() #

Gets the date the post was last modified.

This function will also apply the get_the_modified_date filter to the output.

modified_date( string|null $date_format = null )

Returns: string

NameTypeDescription
$date_formatstring or nullOptional. PHP date format. Will use the date_format option as a default.

Twig

{# Uses date format set in Settings → General #}
Last modified on {{ post.modified_date }}
OR
Last modified on {{ post.modified_date('F jS') }}

HTML

Last modified on January 12, 2015
OR
Last modified on Jan 12th

time() #

Gets the time the post was published to use in your template.

This function will also apply the get_the_time filter to the output.

time( string|null $time_format = null )

Returns: string

NameTypeDescription
$time_formatstring or nullOptional. PHP date format. Will use the time_format option as a default.

Twig

{# Uses time format set in Settings → General #}
Published at {{ post.time }}
OR
Published at {{ post.time|time('G:i') }}

HTML

Published at 1:25 pm
OR
Published at 13:25

modified_time() #

Gets the time of the last modification of the post to use in your template.

This function will also apply the get_the_time filter to the output.

modified_time( string|null $time_format = null )

Returns: string

NameTypeDescription
$time_formatstring or nullOptional. PHP date format. Will use the time_format option as a default.

Twig

{# Uses time format set in Settings → General #}
Published at {{ post.time }}
OR
Published at {{ post.time|time('G:i') }}

HTML

Published at 1:25 pm
OR
Published at 13:25

type() #

Returns the PostType object for a post’s post type with labels and other info.

since 1.0.4

Returns: \Timber\PostType

Twig

This post is from <span>{{ post.type.labels.name }}</span>

HTML

This post is from <span>Recipes</span>

can_edit() #

Checks whether the current user can edit the post.

Returns: bool

Twig

{% if post.can_edit %}
<a href="{{ post.edit_link }}">Edit</a>
{% endif %}

Gets the edit link for a post if the current user has the correct rights.

Returns: string|null The edit URL of a post in the WordPress admin or null if the current user can’t edit the post.

Twig

{% if post.can_edit %}
<a href="{{ post.edit_link }}">Edit</a>
{% endif %}

format() #

Returns: mixed


password_required() #

whether post requires password and correct password has been provided

Returns: bool


get the permalink for a post object

Returns: string ex: http://example.org/2015/07/my-awesome-post

Twig

<a href="{{post.link}}">Read my post</a>

name() #

Returns: string


next() #

Gets the next post that is adjacent to the current post in a collection.

Works pretty much the same as get_next_post().

next( bool|string $in_same_term = false )

Returns: mixed

NameTypeDescription
$in_same_termbool or stringWhether the post should be in a same taxonomy term. Default false.

Twig

{% if post.next %}
<a href="{{ post.next.link }}">{{ post.next.title }}</a>
{% endif %}

pagination() #

Gets a data array to display a pagination for your paginated post.

Use this in combination with {{ post.paged_content }}.

Returns: array An array with data to build your paginated content.

Using simple links to the next an previous page. Twig

{% if post.pagination.next is not empty %}
<a href="{{ post.pagination.next.link|esc_url }}">Go to next page</a>
{% endif %}

{% if post.pagination.prev is not empty %}
<a href="{{ post.pagination.prev.link|esc_url }}">Go to previous page</a>
{% endif %}

Using a pagination for all pages. Twig

{% if post.pagination.pages is not empty %}
<nav aria-label="pagination">
<ul>
{% for page in post.pagination.pages %}
<li>
{% if page.current %}
<span aria-current="page">Page {{ page.title }}</span>
{% else %}
<a href="{{ page.link|esc_ur }}">Page {{ page.title }}</a>
{% endif %}
</li>
{% endfor %}
</ul>
</nav>
{% endif %}

convert() #

Finds any WP_Post objects and converts them to Timber\Post objects.

convert( array|\WP_Post $data )

NameTypeDescription
$dataarray or \WP_Post

parent() #

Gets the parent (if one exists) from a post as a Timber\Post object.

Honors Class Maps.

Returns: bool|\Timber\Post

Twig

Parent page: <a href="{{ post.parent.link }}">{{ post.parent.title }}</a>

path() #

Gets the relative path of a WP Post, so while link() will return http://example.org/2015/07/my-cool-post this will return just /2015/07/my-cool-post

Returns: string

Twig

<a href="{{post.path}}">{{post.title}}</a>

prev() #

Get the previous post that is adjacent to the current post in a collection.

Works pretty much the same as get_previous_post().

prev( bool|string $in_same_term = false )

Returns: mixed

NameTypeDescription
$in_same_termbool or stringWhether the post should be in a same taxonomy term. Default false.

Twig

{% if post.prev %}
<a href="{{ post.prev.link }}">{{ post.prev.title }}</a>
{% endif %}

tags() #

Gets the tags on a post, uses WP's post_tag taxonomy

Returns: array


thumbnail_id() #

Gets the post’s thumbnail ID.

since 2.0.0

Returns: false|int The default post’s ID. False if no thumbnail was defined.


thumbnail() #

get the featured image as a Timber/Image

Returns: \Timber\Image|null of your thumbnail

Twig

<img src="{{ post.thumbnail.src }}" />

title() #

Returns the processed title to be used in templates. This returns the title of the post after WP's filters have run. This is analogous to the_title() in standard WP template tags.

Returns: string

Twig

<h1>{{ post.title }}</h1>

Returns galleries from the post’s content.

gallery( mixed $html = true )

Returns: array A list of arrays, each containing gallery data and srcs parsed from the expanded shortcode.

Twig

{{ post.gallery }}