A few days ago I wrote a post on Fun with WordPress, about writing plugins that expect to be reconfigured. Part of that post was to show how template files could be used in a way that allowed theme authors to automatically override them. This, of course, was heavily inspired by the Habari system which I promised to demonstrate here.

This post demonstrates the Habari method of using theme templates. This time I have included a simplified version of the code that generates the main menu on this site instead of just a list of pages.

If you're writing a plugin in Habari and want to use a template for your plugin output the hard work has already been done. Making the template available can be achieved with a simple one line function in the plugin. This is the function from the example plugin I have written to demonstrate.

  1.  
  2. public function action_init()
  3. {
  4. $this->add_template('funwithmenus', dirname(__FILE__) . '/menu-template.php');
  5. }
  6.  

This registers the a template file in the plugin folder and names it funwithmenus .

The next step is to write a function to output the template. This function will gather the data, pass it to the template page, and then output that template in your theme. Again, here is my example:

  1.  
  2. public function theme_fun_with_menus( $theme )
  3. {
  4. // Get data to output
  5. $menu_data = $this->build_menu( $theme );
  6.  
  7. // Assign the data to be displayed by the plugin's custom template
  8. $theme->menu_data = $menu_data;
  9.  
  10. // Return the output of the custom template
  11. return $theme->fetch( 'funwithmenus' );
  12. }
  13.  

Build menu is the function I use the generate the data for the menu. It returns an array. This is then assigned to the $theme class which is the class that controls all the theme output.

Finally the theme is told to fetch the template that was registered in the first example.

So, to display the menu the following line would be added to the theme:

  1.  
  2. <?php $theme->fun_with_menus(); ?>
  3.  

In the template file the variable $menu_data will be made available to use so a simple menu might look like:

  1.  
  2. <ul id="nav">
  3. <?php foreach ( $menu_data as $menu_item ) { ?>
  4. <li><a href="<?php echo $menu_item['link']; ?>">
  5. <?php echo $menu_item['title']; ?>
  6. </a></li>
  7. <?php } ?>
  8. </ul>
  9.  

If you want to see the full plugin you can download it here.