If you’ve been using WordPress for any amount of time, you’ve probably come across a plugin that asks you to add something to your template. The instructions will say something like:
Insert the following into your theme files where you want the plugin’s widget to appear:
<?php my_plugin_widget() ?>
The slightly more intelligent instructions will understand that the plugin might be deactivated, and suggest you wrap the function in an if()
that checks for its existence:
<?php
if ( function_exists( 'my_plugin_widget' ) ) {
my_plugin_widget();
}
?>
In your own plugins, you can streamline this for the end user by wrapping your function in a custom add_action. How? It’s incredibly easy. Just add an add_action()
to your plugin file, like so:
add_action( 'show_my_plugin_widget', 'my_plugin_widget' );
function my_plugin_widget() {
...
}
Now your users can use one straightforward line in their templates.
<?php do_action('show_my_plugin_widget'); ?>
One short line of code. No worrying about deactivated plugins. A small extra effort on your end can save your end users some frustration down the road.
Next Time: Cold Fusion! (article may be delayed by technical feasibility)
Previously: Use Classes in your WordPress plugins to increase code portability and reduce name conflicts
Nice trick indeed
(I always feel I *have* to comment here to give the spam quizz a try:)
very interesting. I never thought of doing it this way, I’m so used to wrapping all my plugin calls in the if statement. I’ll have to try this out.
I don’t think there is a leaner, cleaner, safer way to extensibly add code to your theme. Great little article Stephen!
Ah, and I thought I was the first one to think of this.
It’s a great idea. The built-in missing-function-proofness is just one of it’s potential benefits.
Pingback: Recent Faves Tagged With "timezone" : MyNetFaves
I am looking for a way I can hide mp3 download path on my wordpress site. Do you have a way I can do this?