Right approach for plugin output styling/template

Make it as simple as possible for theme developers. Most are not programmers. There are two very simple options:

add_theme_support() and get_theme_support()

Provide an identifier and some options. Let’s say your identifier is drtanz_plugin. A theme author could now add the following to her theme’s functions.php:

add_action( 'after_setup_theme', 'prefix_register_theme_support' );

function prefix_register_theme_support()
{
    add_theme_support(
        'drtanz_plugin',
        array (
            'template'   => get_template_directory() . '/templates/drtanz_plugin.php',
            'stylesheet' => FALSE
        )
    );
}

In your plugin you can check the theme support now:

$plugin_options = array (
    'template'      => get_template_directory() . '/templates/drtanz_plugin.php',
    'stylesheet'    => plugins_url( 'default.css', __FILE__ ),
    'show_comments' => TRUE
);

if ( $theme_options = get_theme_support( 'drtanz_plugin' ) )
    $plugin_options = array_merge( $plugin_options, $theme_options );

The theme author did not change the show_comments parameter, so you use the default.

Pro: Easy to extend, really powerful.
Con: Might already be too difficult for some people.

Use locate_template()

I did that in my plugin T5 Opera Speed Dial Preview. Just check if there is a template with a given name in the theme, and try to get the path. If no template was found, use your own.

$template="speed-dial.php";
$path     = locate_template( array ( $template ) );

if ( '' != $path and file_exists( $path ) )
    require $path;
else
    require dirname( __FILE__ ) . "/$template";

Pro: Easy to learn. Just make sure, the name you use is unique. You can add *_theme_support features later if you need them.
Con: It is really just the template, no additional features. And you can not change the template name later, because that would break things.

You can combine both approaches, but I would use just one. It is easier to learn.

Leave a Comment