Use Custom Actions in Your WordPress Plugins

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:

if ( function_exists( '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

This entry was posted in Codecraft, Webcraft and tagged , , , , , , . Bookmark the permalink.

5 Responses to Use Custom Actions in Your WordPress Plugins

  1. Ozh says:

    Nice trick indeed
    (I always feel I *have* to comment here to give the spam quizz a try:)

  2. Dr J says:

    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.

  3. johnbillion says:

    I don’t think there is a leaner, cleaner, safer way to extensibly add code to your theme. Great little article Stephen!

  4. W-Shadow says:

    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.

  5. Pingback: Recent Faves Tagged With "timezone" : MyNetFaves

Leave a Reply

Your email address will not be published.