如何扩展TimberPost

时间:2019-02-26 18:42:27

标签: wordpress twig timber

可能是显而易见的东西,已经藏在我的鼻子下面。

我不明白如何将扩展类与木材挂钩。

我们以问题为例。调用MySitePost时如何获得像Timber::query_post()这样的对象?

  

因此,现在我有一种简单的方法可以在树枝模板中引用{{ post.issue }}。   看起来像一个自动过程...但是我对此不太确定!

供参考: https://timber.github.io/docs/guides/extending-timber/

1 个答案:

答案 0 :(得分:0)

我认为这是一个好问题,可能并不那么明显。

要使用您的自定义帖子,在获取帖子时,您通常会找到一个参数,您可以在其中传递自定义类的名称。返回的对象将成为您的自定义类的实例。

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

当您要获取单个帖子时,它的工作原理非常相似。您可以直接实例化您的帖子,也可以将您的帖子类传递给该函数。

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

如果您想为帖子设置默认的类别,则可以使用Timber\PostClassMap过滤器:

// 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 );
相关问题