Skip to main content
Timber

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

Timber\​Timber

Main class called Timber for this plugin.

PHP

// Get default posts on an archive page
$posts = Timber::get_posts();

// Query for some posts
$posts = Timber::get_posts( [
'post_type' => 'article',
'category_name' => 'sports',
] );

$context = Timber::context( [
'posts' => $posts,
] );

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

Overview #

Methods #

NameReturn TypeSummary/Returns
compile()bool or stringCompiles a Twig file.

Returns: The returned output.
compile_string()bool or stringCompile a string.
context()arrayGets the global context.

Returns: An array of context variables that is used to pass into Twig templates through a render or compile function.
context_global()arrayGets the global context.

Returns: An array of global context variables.
fetch()bool or stringFetch function.

Returns: The returned output.
get_attachment()\Timber\Attachment or nullGets an attachment.

Returns: Timber\Attachment object if an attachment was found, null if no attachment was found.
get_attachment_by()\Timber\Attachment or nullGets an attachment by its URL or absolute file path.
get_comment()\Timber\Comment or nullGets comment.
get_comments()arrayGet comments.
get_context()arrayGet context.
get_external_image()\Timber\ExternalImage or nullGets an external image.
get_image()\Timber\Image or nullGets an image.
get_menu()\Timber\Menu or nullGets a nav menu object.
get_menu_by()\Timber\Menu or nullGets a menu by field.
get_menu_location()string or nullGet the navigation menu location assigned to the given menu.
get_menu_locations()array<string,int or string>Get the navigation menu locations with assigned menus.
get_pages_menu()Gets a menu from the existing pages.
get_pagination()array or mixedGet pagination.
get_post()\Timber\Post or nullGets a Timber Post from a post ID, WP_Post object, a WP_Query object, or an associative array of arguments for WP_Query::__construct().

Returns: Timber\Post object if a post was found, null if no post was found.
get_post_by()\Timber\Post or nullGets a post by title or slug.

Returns: A Timber post or null if no post could be found. If multiple posts with the same slug or title were found, it will select the post with the oldest date.
get_posts()\Timber\PostCollectionInterface or nullGets a collection of posts.

Returns: Null if no query could be run with the used query parameters.
get_sidebar()bool or stringGet sidebar.
get_sidebar_from_php()stringGet sidebar from PHP
get_sites()arrayGet sites.
get_term()\Timber\Term or nullGets a term.
get_term_by()\Timber\Term or nullGets a term by field.
get_terms()iterableGets terms.
get_user()\Timber\User or nullGets a single user.
get_user_by()\Timber\User or nullGets a user by field.
get_users()iterableGets one or more users as an array.

Returns: An array of users objects. Will be empty if no users were found.
get_widgets()stringGet widgets.
query_post()\Timber\Post or array or bool or nullQuery post.
query_posts()\Timber\PostCollectionInterfaceQuery posts.
render()Renders a Twig file.
render_string()Render a string with Twig variables.

Class Methods #

compile() #

Compiles a Twig file.

Passes data to a Twig file and returns the output. If the template file doesn't exist it will throw a warning when WP_DEBUG is enabled.

compile( array|string $filenames, array $data = [], bool|int|array $expires = false, string $cache_mode = Loader::CACHE_USE_DEFAULT, bool $via_render = false )

Returns: bool|string The returned output.

NameTypeDescription
$filenamesarray or stringName or full path of the Twig file to compile. If this is an array of file names or paths, Timber will compile the first file that exists.
$dataarrayOptional. An array of data to use in Twig template.
$expiresbool or int or arrayOptional. In seconds. Use false to disable cache altogether. When passed an array, the first value is used for non-logged in visitors, the second for users. Default false.
$cache_modestringOptional. Any of the cache mode constants defined in Timber\Loader.
$via_renderboolOptional. Whether to apply optional render or compile filters. Default false.

PHP

$data = array(
'firstname' => 'Jane',
'lastname' => 'Doe',
'email' => 'jane.doe@example.org',
);

$team_member = Timber::compile( 'team-member.twig', $data );

compile_string() #

Compile a string.

compile_string( string $string, array $data = [] )

Returns: bool|string

NameTypeDescription
$stringstringA string with Twig variables.
$dataarrayOptional. An array of data to use in Twig template.

PHP

$data = array(
'username' => 'Jane Doe',
);

$welcome = Timber::compile_string( 'Hi {{ username }}, I’m a string with a custom Twig variable', $data );

context() #

Gets the global context.

The context always contains the global context with the following variables:

  • site – An instance of Timber\Site.
  • request - An instance of Timber\Request.
  • theme - An instance of Timber\Theme.
  • user - An instance of Timber\User.
  • http_host - The HTTP host.
  • wp_title - Title retrieved for the currently displayed page, retrieved through wp_title().
  • body_class - The body class retrieved through get_body_class().

The global context will be cached, which means that you can call this function again without losing performance.

In addition to that, the context will contain template contexts depending on which template is being displayed. For archive templates, a posts variable will be present that will contain a collection of Timber\Post objects for the default query. For singular templates, a post variable will be present that that contains a Timber\Post object of the $post global.

since 2.0.0

context( array $extra = [] )

Returns: array An array of context variables that is used to pass into Twig templates through a render or compile function.

NameTypeDescription
$extraarrayAny extra data to merge in. Overrides whatever is already there for this call only. In other words, the underlying context data is immutable and unaffected by passing this param.

context_global() #

Gets the global context.

This function is used by Timber::context() to get the global context. Usually, you don’t call this function directly, except when you need the global context in a partial view.

The global context will be cached, which means that you can call this function again without losing performance.

since 2.0.0

Returns: array An array of global context variables.

PHP

add_shortcode( 'global_address', function() {
return Timber::compile(
'global_address.twig',
Timber::context_global()
);
} );

fetch() #

Fetch function.

DEPRECATED since 2.0.0 use Timber::compile()

fetch( array|string $filenames, array $data = [], bool|int $expires = false, string $cache_mode = Loader::CACHE_USE_DEFAULT )

Returns: bool|string The returned output.

NameTypeDescription
$filenamesarray or stringName of the Twig file to render. If this is an array of files, Timber will render the first file that exists.
$dataarrayOptional. An array of data to use in Twig template.
$expiresbool or intOptional. In seconds. Use false to disable cache altogether. When passed an array, the first value is used for non-logged in visitors, the second for users. Default false.
$cache_modestringOptional. Any of the cache mode constants defined in Timber\Loader.

get_attachment() #

Gets an attachment.

Behaves just like Timber::get_post(), except that it returns null if it finds a Timber\Post that is not an Attachment. Honors Class Maps and falsifies return value after Class Map for the found Timber\Post has been resolved.

see Timber\Timber::get_post()

since 2.0.0

get_attachment( mixed $query = false, array $options = [] )

Returns: \Timber\Attachment|null Timber\Attachment object if an attachment was found, null if no attachment was found.

NameTypeDescription
$querymixedOptional. Query or post identifier. Default false.
$optionsarrayOptional. Options for Timber\Timber::get_post().

get_attachment_by() #

Gets an attachment by its URL or absolute file path.

Honors the timber/post/image_extensions filter, returning a Timber\Image if the found attachment is identified as an image. Also honors Class Maps.

since 2.0.0

get_attachment_by( string $field_or_ident, string $ident = '' )

Returns: \Timber\Attachment|null

NameTypeDescription
$field_or_identstringCan be "url", "path", an attachment URL, or the absolute path of an attachment file. If "url" or "path" is given, a second arg is required.
$identstringOptional. An attachment URL or absolute path. Default empty string.

PHP

// Get attachment by URL.
$attachment = Timber::get_attachment_by( 'url', 'https://example.com/uploads/2020/09/cat.gif' );

// Get attachment by filepath.
$attachment = Timber::get_attachment_by( 'path', '/path/to/wp-content/uploads/2020/09/cat.gif' );

// Try to handle either case.
$mystery_string = some_function();
$attachment = Timber::get_attachment_by( $mystery_string );

get_comment() #

Gets comment.

since 2.0.0

get_comment( int|\WP_Comment $comment )

Returns: \Timber\Comment|null

NameTypeDescription
$commentint or \WP_Comment

get_comments() #

Get comments.

since 2.0.0

get_comments( array|\WP_Comment_Query $query = [], array $options = [] )

Returns: array

NameTypeDescription
$queryarray or \WP_Comment_Query
$optionsarrayOptional. None are currently supported.

get_context() #

Get context.

DEPRECATED since 2.0.0, use Timber::context() instead.

Returns: array


get_external_image() #

Gets an external image.

Behaves just like Timber::get_image(), except that you can use an absolute or relative path or a URL to load an image. You can also pass in an external URL. In that case, Timber will sideload the image and store it in the uploads folder of your WordPress installation. The next time the image is accessed, it will be loaded from there.

see Timber\Timber::get_image()

since 2.0.0

get_external_image( bool $url = false, array $args = [] )

Returns: \Timber\ExternalImage|null

NameTypeDescription
$urlboolImage path or URL. The path can be absolute or relative to the WordPress installation.
$argsarrayAn associative array with additional arguments for the image.

  • $alt
    string Alt text for the image.
  • $caption
    string Caption text for the image.

get_image() #

Gets an image.

Behaves just like Timber::get_post(), except that it returns null if it finds a Timber\Post that is not an Image. Honors Class Maps and falsifies return value after Class Map for the found Timber\Post has been resolved.

see Timber\Timber::get_post()

since 2.0.0

get_image( mixed $query = false, array $options = [] )

Returns: \Timber\Image|null

NameTypeDescription
$querymixedOptional. Query or post identifier. Default false.
$optionsarrayOptional. Options for Timber\Timber::get_post().

get_menu() #

Gets a nav menu object.

since 2.0.0

get_menu( int|string $identifier = null, array $args = [] )

Returns: \Timber\Menu|null

NameTypeDescription
$identifierint or stringA menu identifier: a term_id, slug, menu name, or menu location name
$argsarrayAn associative array of options. Currently only one option is supported: - depth: How deep down the tree of menu items to query. Useful if you only want the first N levels of items in the menu.

PHP

// Get a menu by location
$menu = Timber::get_menu( 'primary-menu' );

// Get a menu by slug
$menu = Timber::get_menu( 'my-menu' );

// Get a menu by name
$menu = Timber::get_menu( 'Main Menu' );

// Get a menu by ID (term_id)
$menu = Timber::get_menu( 123 );

get_menu_by() #

Gets a menu by field.

since 2.0.0

get_menu_by( string $field, int|string $value, array $args = [] )

Returns: \Timber\Menu|null

NameTypeDescription
$fieldstringThe name of the field to retrieve the menu with. One of: id, ID, term_id, slug, name or location.
$valueint or stringThe value to search for by $field.

PHP

// Get a menu by location.
$menu = Timber::get_menu_by( 'location', 'primary' );

// Get a menu by slug.
$menu = Timber::get_menu_by( 'slug', 'primary-menu' );

get_menu_location() #

Get the navigation menu location assigned to the given menu.

since 2.3.0

get_menu_location( \WP_Term|int $term )

Returns: string|null

NameTypeDescription
$term\WP_Term or intThe menu to find; either a WP_Term object or a Term ID.

get_menu_locations() #

Get the navigation menu locations with assigned menus.

since 2.3.0

Returns: array<string,int|string>


get_pages_menu() #

Gets a menu from the existing pages.

since 2.0.0

get_pages_menu( array $args = [] )

NameTypeDescription
$argsarrayOptional. Arguments for wp_list_pages(). Timber doesn’t use that function under the hood, but supports all arguments for that function. It will use get_pages() to get the pages that will be used for the Pages Menu.

PHP

$menu = Timber::get_pages_menu();

get_pagination() #

Get pagination.

DEPRECATED since 2.0.0

link https://timber.github.io/docs/v2/guides/pagination/

get_pagination( array $prefs = [] )

Returns: array|mixed

NameTypeDescription
$prefsarrayan array of preference data.

get_post() #

Gets a Timber Post from a post ID, WP_Post object, a WP_Query object, or an associative array of arguments for WP_Query::__construct().

By default, Timber will use the Timber\Post class to create a new post object. To control which class is instantiated for your Post object, use Class Maps

see https://developer.wordpress.org/reference/classes/wp_query/__construct/

get_post( mixed $query = false, array $options = [] )

Returns: \Timber\Post|null Timber\Post object if a post was found, null if no post was found.

NameTypeDescription
$querymixedOptional. Post ID or query (as an array of arguments for WP_Query). If a query is provided, only the first post of the result will be returned. Default false.
$optionsarrayOptional associative array of options. Defaults to an empty array.

PHP

// Using a post ID.
$post = Timber::get_post( 75 );

// Using a WP_Post object.
$wp_post = get_post( 123 );
$post = Timber::get_post( $wp_post );

// Using a WP_Query argument array
$post = Timber::get_post( [
'post_type' => 'page',
] );

// Use currently queried post. Same as using get_the_ID() as a parameter.
$post = Timber::get_post();

// From an associative array with an `ID` key. For ACF compatibility. Using this
// approach directly is not recommended. If you can, configure the return type of your
// ACF field to just the ID.
$post = Timber::get_post( get_field('associated_post_array') ); // Just OK.
$post = Timber::get_post( get_field('associated_post_id') ); // Better!

get_post_by() #

Gets a post by title or slug.

since 2.0.0

get_post_by( string $type, string $search_value, array $args = [] )

Returns: \Timber\Post|null A Timber post or null if no post could be found. If multiple posts with the same slug or title were found, it will select the post with the oldest date.

NameTypeDescription
$typestringThe type to look for. One of slug or title.
$search_valuestringThe post slug or post title to search for. When searching for title, this parameter doesn’t need to be case-sensitive, because the = comparison is used in MySQL.
$argsarrayOptional. An array of arguments to configure what is returned.

  • $post_type
    string or array Optional. What WordPress post type to limit the results to. Defaults to 'any'
  • $order_by
    string Optional. The field to sort by. Defaults to 'post_date'
  • $order
    string Optional. The sort to apply. Defaults to ASC

PHP

// By slug
$post = Timber::get_post_by( 'slug', 'about-us' );

// By title
$post = Timber::get_post_by( 'title', 'About us' );

get_posts() #

Gets a collection of posts.

Refer to the official documentation for WP_Query for a list of all the arguments that can be used for the $query parameter.

get_posts( mixed $query = false, array $options = [] )

Returns: \Timber\PostCollectionInterface|null Null if no query could be run with the used query parameters.

NameTypeDescription
$querymixedOptional. Query args. Default false, which means that Timber will use the global query. Accepts an array of WP_Query arguments, a WP_Query instance or a list of post IDs.
$optionsarrayOptional. Options for the query.

  • $merge_default
    bool Merge query parameters with the default query parameters of the current template. Default false.

PHP

// Use the global query.
$posts = Timber::get_posts();

// Using the WP_Query argument format.
$posts = Timber::get_posts( [
'post_type' => 'article',
'category_name' => 'sports',
] );

// Using a WP_Query instance.
$posts = Timber::get_posts( new WP_Query( [ 'post_type' => 'any' ) );

// Using an array of post IDs.
$posts = Timber::get_posts( [ 47, 543, 3220 ] );

get_sidebar() #

Get sidebar.

get_sidebar( string $sidebar = 'sidebar.php', array $data = [] )

Returns: bool|string

NameTypeDescription
$sidebarstring
$dataarray

get_sidebar_from_php() #

Get sidebar from PHP

get_sidebar_from_php( string $sidebar = '', array $data = [] )

Returns: string

NameTypeDescription
$sidebarstring
$dataarray

get_sites() #

Get sites.

get_sites( array|bool $blog_ids = false )

Returns: array

NameTypeDescription
$blog_idsarray or bool

get_term() #

Gets a term.

get_term( int|\WP_Term $term = null )

Returns: \Timber\Term|null

NameTypeDescription
$termint or \WP_TermA WP_Term or term_id

PHP

// Get a Term.
$tag = Timber::get_term( 123 );

get_term_by() #

Gets a term by field.

This function works like get_term_by(), but returns a Timber\Term object.

since 2.0.0

get_term_by( string $field, int|string $value, string $taxonomy = '' )

Returns: \Timber\Term|null

NameTypeDescription
$fieldstringThe name of the field to retrieve the term with. One of: id, ID, slug, name or term_taxonomy_id.
$valueint or stringThe value to search for by $field.
$taxonomystringThe taxonomy you want to retrieve from. Empty string will search from all.

PHP

// Get a term by slug.
$term = Timber::get_term_by( 'slug', 'security' );

// Get a term by name.
$term = Timber::get_term_by( 'name', 'Security' );

// Get a term by slug from a specific taxonomy.
$term = Timber::get_term_by( 'slug', 'security', 'category' );

get_terms() #

Gets terms.

see https://developer.wordpress.org/reference/classes/wp_term_query/__construct/

get_terms( string|array $args = null, array $options = [] )

Returns: iterable

NameTypeDescription
$argsstring or arrayA string or array identifying the taxonomy or WP_Term_Query args. Numeric strings are treated as term IDs; non-numeric strings are treated as taxonomy names. Numeric arrays are treated as a list a of term identifiers; associative arrays are treated as args for WP_Term_Query::__construct() and accept any valid parameters to that constructor. Default null, which will get terms from all queryable taxonomies.
$optionsarrayOptional. None are currently supported. Default empty array.

PHP

// Get all tags.
$tags = Timber::get_terms( 'post_tag' );
// Note that this is equivalent to:
$tags = Timber::get_terms( 'tag' );
$tags = Timber::get_terms( 'tags' );

// Get all categories.
$cats = Timber::get_terms( 'category' );

// Get all terms in a custom taxonomy.
$cats = Timber::get_terms('my_taxonomy');

// Perform a custom Term query.
$cats = Timber::get_terms( [
'taxonomy' => 'my_taxonomy',
'orderby' => 'slug',
'order' => 'DESC',
] );

get_user() #

Gets a single user.

By default, Timber will use the Timber\User class to create a your post objects. To control which class is used for your post objects, use Class Maps.

since 2.0.0

get_user( int|\WP_User $user = null )

Returns: \Timber\User|null

NameTypeDescription
$userint or \WP_UserA WP_User object or a WordPress user ID. Defaults to the ID of the currently logged-in user.

PHP

$current_user = Timber::get_user();

// Get user by ID.
$user = Timber::get_user( $user_id );

// Convert a WP_User object to a Timber\User object.
$user = Timber::get_user( $wp_user_object );

// Check if a user is logged in.

$user = Timber::get_user();

if ( $user ) {
// Yay, user is logged in.
}

get_user_by() #

Gets a user by field.

This function works like get_user_by(), but returns a Timber\User object.

since 2.0.0

get_user_by( string $field, int|string $value )

Returns: \Timber\User|null

NameTypeDescription
$fieldstringThe name of the field to retrieve the user with. One of: id, ID, slug, email or login.
$valueint or stringThe value to search for by $field.

PHP

// Get a user by email.
$user = Timber::get_user_by( 'email', 'user@example.com' );

// Get a user by login.
$user = Timber::get_user_by( 'login', 'keanu-reeves' );

get_users() #

Gets one or more users as an array.

By default, Timber will use the Timber\User class to create a your post objects. To control which class is used for your post objects, use Class Maps.

since 2.0.0

get_users( array $query = [], array $options = [] )

Returns: iterable An array of users objects. Will be empty if no users were found.

NameTypeDescription
$queryarrayOptional. A WordPress-style query or an array of user IDs. Use an array in the same way you would use the $args parameter in WP_User_Query. See WP_User_Query::prepare_query() for a list of all available parameters. Passing an empty parameter will return an empty array. Default empty array [].
$optionsarrayOptional. An array of options. None are currently supported. This parameter exists to prevent future breaking changes. Default empty array [].

PHP

// Get users with on an array of user IDs.
$users = Timber::get_users( [ 24, 81, 325 ] );

// Get all users that only have a subscriber role.
$subscribers = Timber::get_users( [
'role' => 'subscriber',
] );

// Get all users that have published posts.
$post_authors = Timber::get_users( [
'has_published_posts' => [ 'post' ],
] );

get_widgets() #

Get widgets.

get_widgets( int|string $widget_id )

Returns: string

NameTypeDescription
$widget_idint or stringOptional. Index, name or ID of dynamic sidebar. Default 1.

query_post() #

Query post.

DEPRECATED since since 2.0.0 Use Timber::get_post() instead.

query_post( mixed $query = false, array $options = [] )

Returns: \Timber\Post|array|bool|null


query_posts() #

Query posts.

DEPRECATED since since 2.0.0 Use Timber::get_posts() instead.

query_posts( mixed $query = false, array $options = [] )

Returns: \Timber\PostCollectionInterface


render() #

Renders a Twig file.

Passes data to a Twig file and echoes the output.

render( array|string $filenames, array $data = [], bool|int|array $expires = false, string $cache_mode = Loader::CACHE_USE_DEFAULT )

NameTypeDescription
$filenamesarray or stringName or full path of the Twig file to render. If this is an array of file names or paths, Timber will render the first file that exists.
$dataarrayOptional. An array of data to use in Twig template.
$expiresbool or int or arrayOptional. In seconds. Use false to disable cache altogether. When passed an array, the first value is used for non-logged in visitors, the second for users. Default false.
$cache_modestringOptional. Any of the cache mode constants defined in Timber\Loader.

PHP

$context = Timber::context();

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

render_string() #

Render a string with Twig variables.

render_string( string $string, array $data = [] )

NameTypeDescription
$stringstringA string with Twig variables.
$dataarrayAn array of data to use in Twig template.

PHP

$data = array(
'username' => 'Jane Doe',
);

Timber::render_string( 'Hi {{ username }}, I’m a string with a custom Twig variable', $data );