WordPress Plugin Actions


WordPress actions allow you as a plugin author to be able to hook into the WordPress application and execute a piece of code. An example of an action would be that you want a execute some code after a user has published a post or left a comment.

Some of the actions that I use heavily are:

  • admin_menu: Allows you to set up an admin panel for your plugin.
  • wp_head: Allows you to insert code into the tag of a blog

Actions in Action:

While defining the structure of a WordPress plugin, I left a place holder for some actions. In this example, we are going to set up a piece of code that will run inside the <head>tag of a WordPress blog.
First we need to add a function into our DevloungePluginSeries class.
PHP:
1. function addHeaderCode() {
2.            ?>
3. <!– Devlounge Was Here –>
4.            <?php
5.
6.        }
All the above function does is output an HTML comment. Rather simple, but you could
output just about anything. To call this function, we add an action.
PHP:
1. //Actions and Filters
2. if (isset($dl_pluginSeries)) {
3.     //Actions
4.     add_action(‘wp_head’, array(&$dl_pluginSeries, ‘addHeaderCode’), 1);
5.     //Filters
6. }
From the WordPress Plugin API page, the add_action structure is as follows:
add_action ( ‘hook_name’, ‘your_function_name’, [priority], [accepted_args] );
Since we are calling a function inside of a class, we pass the action an array with a reference to our class variable (dl_pluginSeries) and the function name we wish to call (addHeaderCode). We have given our plugin a priority level of 1, with lower numbers executed first.

Running the Code:

If the Devlounge Plugin Series plugin is activated, the comment of “Devlounge was here” should show up when you go to View->Source in your web browser when looking at your main blog site.

Removing Actions:

If your plugin dynamically adds actions, you can dynamically remove actions as well with the remove_actions function. The structure is as follows:
remove_action(‘action_hook’,’action_function’).

Advertisements
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: