Timber 2.X中自定义页面模板的自定义Post类实现方法
在Timber 2.X中创建自定义页面模板类的正确方法
1. 调整自定义Post类的构造函数
Timber 2.X对Timber\Post的构造逻辑做了改动,子类构造需要适配新的参数规则,确保正确传递内容给父类:
class MyPage extends \Timber\Post { public function __construct($post = null, array $args = []) { parent::__construct($post, $args); // 这里写你的自定义构造逻辑 } // 自定义方法示例 public function get_custom_meta() { return get_post_meta($this->ID, 'custom_meta_key', true); } }
继承自定义类的子类写法:
class MyCustomPage extends MyPage { public function __construct($post = null, array $args = []) { parent::__construct($post, $args); // 子类的自定义构造逻辑 } // 子类自定义方法示例 public function get_child_custom_content() { return '仅自定义页面模板显示的内容'; } }
2. 推荐:配置类映射自动关联
在主题的functions.php中添加类映射,让Timber自动为特定页面模板或帖子类型使用自定义类,不用手动实例化:
add_filter('timber/post/classmap', function($classmap) { // 所有页面类型默认使用MyPage类 $classmap['page'] = MyPage::class; // 为template-custom-page.php模板指定MyCustomPage类 // 规则是:{帖子类型}-{模板slug},模板slug是去掉template-和.php后的部分 $classmap['page-custom-page'] = MyCustomPage::class; return $classmap; });
配置后,在模板中直接用Timber::context()就能自动拿到MyCustomPage实例:
$context = \Timber::context(); Timber::render('template-custom-page.twig', $context);
3. 手动实例化的正确方式
如果一定要手动在模板中创建实例,必须显式传递当前帖子的ID或WP_Post对象,不能空参数调用:
$context = \Timber::context(); // 传递当前帖子ID $context['post'] = new MyCustomPage(get_the_ID()); // 或者用from静态方法更简洁 // $context['post'] = MyCustomPage::from(get_the_ID()); Timber::render('template-custom-page.twig', $context);
旧方法返回空对象的原因
Timber 2.X中,Timber\Post的构造函数不再自动加载当前帖子,空参数调用时不会初始化任何内容,所以返回空对象。必须显式传递帖子ID或WP_Post对象才能正确实例化。
内容的提问来源于stack exchange,提问作者Enrico Cassinelli
相关产品推荐
相关产品推荐

