Skip to content

Class Maps

The Class Map is the central hub for Timber to select the right PHP class for post or term objects. Whenever you want to extend existing Timber classes with your custom classes, you’ll have to register them through a Class Map so that Timber will know when to use it.

There are several different Class Maps in Timber:

  • timber/post/classmap for posts
  • timber/term/classmap for terms
  • timber/comment/classmap for comments
  • timber/menu/classmap and timber/menu/class for menus
  • timber/menuitem/classmap and timber/menuitem/class for menu item classes
  • timber/user/class for users

You can use class maps for teasers who require additional data (like custom fields) or for custom fields that are repeated between multiple pages.

Let’s create one together!

We have created a custom field called Amount of pages (amount_of_pages) for the post type Book, and we want to display this field on the front page.

Use the CLI to scaffold the class:

Terminal window
wp instance make classmap-post --post-type=book
# → app/Classmap/Post/BookClassmapPost.php
# → registered in app/Hook/TimberClassmapHook.php automatically

Or create it manually in app/Classmap/Post/. Every post classmap must extend Timber\Post:

app/Classmap/Post/BookClassmapPost.php
<?php
namespace App\Classmap\Post;
use Timber\Post as TimberPost;
class BookClassmapPost extends TimberPost
{
}

Add a method for your custom field. The method name becomes the variable name in Twig:

class BookClassmapPost extends TimberPost
{
public function amount_of_pages(): mixed
{
return $this->meta('amount_of_pages');
}
}

Open app/Hook/TimberClassmapHook.php and add your class to the posts method:

app/Hook/TimberClassmapHook.php
use App\Classmap\Post\BookClassmapPost;
class TimberClassmapHook implements HookContract
{
public function posts(array $classmap): array
{
$customPostClassmap = [
'book' => BookClassmapPost::class,
];
return array_merge($classmap, $customPostClassmap);
}
}

The array key is the post type slug (book) and the value is your class.

front-page.php
$context = Timber::context();
$context['post'] = Timber::get_post();
$context['book'] = Timber::get_post(8); // Timber will use BookClassmapPost automatically
Timber::render('templates/front-page.twig', $context);
{# views/templates/front-page.twig #}
{% block content %}
{{ post.title }}
{{ book.amount_of_pages }}
{% endblock %}

For more detail on how class maps work internally, see the Timber class maps documentation.