hitech95
hitech95

Reputation: 55

How to extends a TimberPost

Probably it is something obvious and has escaped under my nose.

I did not understand how to hook my extended class to timber.

Let's take the example of the issues. How can I get an object like MySitePost when I call Timber::query_post()?

So now I’ve got an easy way to refer to the {{ post.issue }} in our twig templates. Looks like an automatic process... but I'm not so sure about this!

For reference: https://timber.github.io/docs/guides/extending-timber/

Upvotes: 0

Views: 1098

Answers (1)

Gchtr
Gchtr

Reputation: 2794

I think this is a good question that might not be so obvious.

To use your custom post, you’ll often find a parameter when fetching posts where you can pass the name of your custom class. The returned object will then be instances of your custom class.

$posts = Timber::get_posts( $your_args, 'MySitePost' );
$posts = new Timber\PostQuery( $your_args, 'MySitePost' );

When you want to fetch a single post, it works quite similar. You can either directly instantiate your post or pass your post class to the function.

$post = new MySitePost();
$post = Timber::get_post( $post_id, 'MySitePost' );

If you want to set a default class to be used for your posts, you can use the Timber\PostClassMap filter:

// Use one class for all Timber posts.
add_filter( 'Timber\PostClassMap', function( $post_class, $post_type ) {
   return 'MySitePost';
}, 10, 2 );

// Use default class for all post types, except for pages.
add_filter( 'Timber\PostClassMap', function( $post_class, $post_type ) {
   // Bailout if not a page
   if ( 'page' !== $post_type ) {
       return $post_class;
   }

   return 'MySitePost';
}, 10, 2 );

// Use a class map for different post types
add_filter( 'Timber\PostClassMap', function( $post_class, $post_type ) {
   return array(
       'post'      => 'MySitePost',
       'apartment' => 'MyApartmentPost',
       'city'      => 'MyCityPost',
   );
}, 10, 2 );

Upvotes: 8

Related Questions