请注意,根据WP标准,插件都是“控制器”。
这取决于插件应该做什么,但在所有情况下,我都会尽量将屏幕输出与PHP代码分离。
有一种方法可以轻松做到这一点-首先,定义一个加载模板的函数:
function my_plugin_load_template(array $_vars){
// you cannot let locate_template to load your template
// because WP devs made sure you can\'t pass
// variables to your template :(
$_template = locate_template(\'my_plugin\', false, false);
// use the default one if the theme doesn\'t have it
if(!_$template)
$_template = \'views/template.php\';
// load it
extract($_vars);
require $template;
}
现在,如果插件使用小部件显示数据:
class Your_Widget extends WP_Widget{
...
public function widget($args, $instance){
$title = apply_filters(\'widget_title\', $instance[\'title\'], $instance, $this->id_base);
// this widget shows the last 5 "movies"
$posts = new WP_Query(array(\'posts_per_page\' => 5, \'post_type\' => \'movie\'));
if($title)
print $before_title . $title . $after_title;
// here we rely on the template to display the data on the screen
my_plugin_load_template(array(
// variables you wish to expose in the template
\'posts\' => $posts,
));
print $before_widget;
}
...
}
模板:
<?php while($posts->have_posts()): $posts->the_post(); ?>
<p><?php the_title(); ?></p>
<?php endwhile; ?>
文件:
/plugins/my_plugin/plugin.php <-- just hooks
/plugins/my_plugin/widget.php <-- widget class, if you have a widget
/themes/twentyten/my_plugin.php <-- template
/plugins/my_plugin/views/template.php <-- fallback template
你把CSS、JS、图像放在哪里,或者你如何为钩子设计容器就不那么重要了。我想这是个人喜好的问题。