Class Maps
What Are Class Maps?
Section titled “What Are 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/classmapfor poststimber/term/classmapfor termstimber/comment/classmapfor commentstimber/menu/classmapandtimber/menu/classfor menustimber/menuitem/classmapandtimber/menuitem/classfor menu item classestimber/user/classfor users
When Would I Use These?
Section titled “When Would I Use These?”You can use class maps for teasers who require additional data (like custom fields) or for custom fields that are repeated between multiple pages.
How Do I Use Them?
Section titled “How Do I Use Them?”Let’s create one together!
Scenario
Section titled “Scenario”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.
Let’s Get Started
Section titled “Let’s Get Started”Creating the book class
Section titled “Creating the book class”Use the CLI to scaffold the class:
wp instance make classmap-post --post-type=book# → app/Classmap/Post/BookClassmapPost.php# → registered in app/Hook/TimberClassmapHook.php automaticallyOr create it manually in app/Classmap/Post/. Every post classmap must extend Timber\Post:
<?php
namespace App\Classmap\Post;
use Timber\Post as TimberPost;
class BookClassmapPost extends TimberPost{}Adding the custom field
Section titled “Adding the custom field”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'); }}Registering the class map
Section titled “Registering the class map”Open app/Hook/TimberClassmapHook.php and add your class to the posts method:
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.
Using it in a template
Section titled “Using it in a template”$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.

