creativecoder / wp-template-controller
为您的WordPress模板生成抽象数据
1.0.1
2015-01-19 13:11 UTC
Requires
- php: >=5.3.0
This package is not auto-updated.
Last update: 2024-09-28 16:53:08 UTC
README
此类允许您将主题模板所需的数据从模板文件本身(如 page.php
和 single.php
)抽象出来。使用控制器文件生成数据,并让模板文件专注于显示这些数据。
安装
在主题或插件中包含类和控制器文件
// Example: require_once( get_template_directory() . '/lib/classes/class-template-controller.php' ); require_once( get_template_directory() . '/controller.php' );
用法
在控制器文件中,扩展该类以创建主题的控制器。类中的每个方法都应该匹配要显示数据的模板的body类。common()
方法为所有模板触发。别忘了初始化类。
class My_Controller extends Template_Controller { // Generates data for all templates public function common() { $this->add( 'hi', 'I load for every template on the site.' ); } public function page() { $this->add( 'yo', 'I load for page.php and custom page templates.' ); // Get recent posts to display on the page $this->add( 'recent_posts', get_posts( array( 'post_type' => 'post', 'posts_per_page' => 2, ) ) ); } } My_Controller::init();
在您的模板文件中,调用您生成的数据。
// within page.php // Store the data $yo = get_tpl_data( 'yo' ); // Echo out the data tpl_data( 'hi' ); // Use data as you normally would in template files $recent_posts = tpl_data( 'recent_posts' ); foreach( $recent_posts as $post ) { echo $post->post_title; }
或者,您可以通过调用全局变量来获取该模板可用的所有数据。
// within page.php global $template_data; extract( $template_data, EXTR_SKIP ); echo $yo; foreach( $recent_posts as $post ) { echo $post->post_title; }
多个控制器
您可以创建和初始化任意多的子类。所有类都将遵循相同的模式,加载与模板的任何body类匹配的方法。所有数据都静态存储在父类中,因此可以使用tpl_data函数轻松调用。
感谢 @DesignPlug 的想法: https://github.com/DesignPlug/wxp-dom-router