This article assumes that you’ve read Writing a Plugin, giving an overview (and many details) of how to develop a plugin. The same speaks specifically about the API “Hooks”, also known as “Filters” and “Actions”, used by WordPress to set your plugin at runtime.
These hooks can also be used in themes, as described here.
Hooks are provided by WordPress to allow your plugin to ‘hook into’ the rest of WordPress; that is, to call functions in your plugin at specific times, and thereby set your plugin in motion. There are two kinds of hooks:
You can sometimes accomplish the same goal with either an action or a filter. For example, if you want your plugin to change the text of a post, you might add an action function to publish_post (so the post is modified as it is saved to the database), or a filter function to the_content (so the post is modified as it is displayed in the browser screen).
For a thorough listing of all action and filter hooks in WP see Adam Brown’s WordPress Hooks Database.
|
Actions Functions |
---|
|
Activation/Deactivation/Uninstall Functions | |
---|---|
|
|
Actions are triggered by specific events that take place in WordPress, such as publishing a post, changing themes, or displaying an administration screen. An Action is a custom PHP function defined in your plugin (or theme) and hooked, i.e. set to respond, to some of these events. Actions usually do one or more of the following:
The basic steps to make this happen (described in more detail below) are:
The first step in creating an action in your plugin is to create a PHP function with the action functionality of your plugin and put it in your plugin file (your plugin file must go into the wp-content/plugins directory). For example, if you want your friends to get an email message whenever you create a new post, you might define the following function:
function email_friends($post_ID) { $friends = 'bob@example.org,susie@example.org'; mail($friends, "sally's blog updated", 'I just put something on my blog: http://blog.example.com'); return $post_ID; }
For most actions, your function should accept a single parameter (usually the post or comment ID, depending on the action). Some actions take more than one parameter — check the documentation for the action (if available) or the WordPress source code for more information. Besides the one parameter, you can also access the global variables of WordPress, and call other WordPress functions (or functions in your plugin file).
Any text output by the function (e.g. with print) will appear in the page source at the location where the action was invoked.
NOTE: Keep in mind that other plugins or the WordPress core may already be using the function name you have thought of. See the next section, Avoiding Function Name Collisions for more information.