I am creating a plugin that needs to output things on the front end of the site. I tried keeping the default look as clean as possible, but I’d also like to make it easy for the users to modify.
My thinking is to include the ability to load a custom stylesheet instead of the default one, if the user creates a stylesheet with a particular name in his theme. Any pointers on how to build that functionality?
In the more extreme case that the user wants to change the HTML/PHP used for output completely, I created an action and attached my display function to that action. In this way, a user is able to unattach my default display function, and attach his custom display function via the available hook.
Is this the right approach to go about this?
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.