WordPress Development: Actions

Published on Jan 28, 2009   //  Development, WordPress
Off

WordPress Development

This week on the WordPress Development series, we’ll be talking about another vital part of the WordPress Plugin API, actions.

As with filters, actions are fairly simple. They are used to hook into WordPress at certain points during execution to do something at that point. For example, you could make a plugin that hooks into the post publishing action, so that you could send an email everytime a post was published.

Using an action is very similar to using a filter. We first need to determine what we intend on using an action for, then we need to find the appropriate action. For this example, we’re going to add a tag to the head section of the current theme. For this, we will use the action wp_head (a list of available actions is available here). If you need to use some parameters that the action is passing to your function, you may need to look up the action declaration within WordPress’ source (actions are declared with do_action(). However, for this example, we do not need any parameters (and wp_head doesn’t provide any.

Alright, now let’s write a function that will add a tag to the head of the theme.

[code='php']function add_tag_to_head() {
echo ' ';
}[/code]

Unlike filters, actions tend to either just not output anything or to echo something. Returning something from an action won’t do much. Echoing in an action works because action are placed at certain points in WordPress’ execution of a page (or event). For instance, the wp_head action is usually located right before the ending head tag; meaning anything echoed to this action will appear before the ending head tag.

Now, we need to actually hook this function into the action. We do this by using the add_action function.

[code='php']add_action( 'wp_head', 'add_tag_to_head' );[/code]

The add_action function is identical to the add_filter function, just one works for actions and the other works for filters. The first argument (or parameter, if you want) is the name of the action we want to hook in to. The second argument is the name of the function that will be hooked into the action. There are also third and fourth optional arguments. The third argument is the priorty of when this action should be run. The default of this is 10, however if you need to have your action run earlier or later than other actions, you would lower or raise (respectively) this number. Otherwise, actions will just be executing in order. The fourth parameter is the number of arguments your function can accept, the default is 1 (there’s no need to make this 0 if the action doesn’t pass any arguments).

Conclusion

You should now be another step closer to completely understanding the WordPress Plugin API. Filters and actions are the most important part of the API.