Saturday 21 November 2015

WordPress Action Hooks and Filter Hooks

Introduction

This page documents the API (Application Programming Interface) hooks available to WordPress plugin developers, and how to use them.

This article assumes you have already read Writing a Plugin, which gives an overview (and many details) of how to develop a plugin. This article is specifically about the API of "Hooks", also known as "Filters" and "Actions", that WordPress uses to set your plugin in motion.
These hooks may also be used in themes, as described here.

Hooks, Actions and Filters

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:
  1. Actions (Codex Action Reference)
  2. Filters (Codex Filter Reference)
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

Action Hooks

Action hooks allow you to execute your custom functions which are referred to as actions.
Action hooks allow you to add additional code to the WordPress core or theme so that you can achieve some new functionality or customizations.
The actions or functions which you would write for your plugin or theme can be run wherever there is a hook available – which may be during the WordPress loading stage or when certain events occur.
Some examples of events where you might want to execute an action are when someone publishes a blog post or when a certain type of page is being viewed.
Each of these “events” will contain an appropriate hook onto which you can attach your action (or function) to.
The definition of action hooks as stated in the WordPress documentation is:
“Actions are the hooks that the WordPress core launches at specific points during execution, or when specific events occur. Your plugin can specify that one or more of its PHP functions are executed at these points, using the Action API.”
So what does an action hook look like?
In the WordPress core system hooks are usually created by writing a function which contains inside of it a command which represents the particular hook.
Let’s look at an example of a very commonly used action hook called wp_head which is used by many plugins and themes to add things such as meta data between the <head> </head> tags of a WordPress page:

function wp_head() {
do_action('wp_head');
}

(Note: The above snippet was taken directly from the core WordPress code in the file wp-includes/general-template.php).
The tell-tale characteristic which identifies the above code as an action hook is the presence of the function:

do_action('wp_head');

In other words, the do_action function is how the ‘wp_head’ action hook is created.
A generic way of representing an action hook is:

do_action($tag, $args)

where:
$tag = the name of the action hook (eg, wp_head)
$args = optional parameter(s) passed to the actions (or functions written by you) which register with the particular action hook. Action hooks can have many or no parameters such as the wp_head example shown above.
(Note: You should consult the WordPress code to determine if or how many parameters an action hook has)
Another way you might see an action hook created is via the following function:

do_action_ref_array( $tag, $args );

The above function differs slightly to the do_action function in that the $args variable represents an array of parameters which are mandatory.
Without going into the technical details too much, it is simply enough to know that whenever you see a do_action() or do_action_ref_array() function, then you know that you are dealing with an action hook.
So now we know what action hooks look like, how do we write actions which we can use to hook into these hooks?
When you are writing your custom functions for your plugin or theme, you would typically hook your code into an action hook using a statement like the following:

add_action( 'action_hook', 'your_function_name' );

The above line tells WordPress that you would like to execute your function called your_function_name when the system comes across the action hook called action_hook.
Below is a simple example of using an action hook by creating an action:

<?php
add_action( 'wp_head', 'my_actionhook_example' );
function my_actionhook_example() {
echo '<meta name="description" content="Hello world. This meta description was created using my action hook example." />' . "\n";
} // The end of my_actionhook_example()
?>

The above code is something which you might place in your theme or child-theme’s functions.php file and when it is executed it will simply echo a meta tag inside the head portion of a WordPess page.
The add_action line registers (or hooks) your action (called my_actionhook_example) to the action hook which is called wp_head.
If you recall from earlier we said that an action is a customized function which you create and in the example above you can see the function definition and the code for the function which simply adds some meta data.
The example we’ve just seen uses one of a large number of action hooks available to you in WordPress and is a small drop in the ocean with what you can do with action hooks.
If you are curious and want to discover more of the action action hooks available you can do a global search through the WordPress core code for the following two strings using a code editor:
do_action
do_action_ref_array
The search results yielding the above terms will contain the action hooks built into WordPress where the first parameter will be the action hook name.
Also don’t forget that the WordPress documentation and codex is also a great source of information about hooks too.

Filter Hooks

Filter hooks are another type of WordPress hook and these deal with the manipulation of text and other output.
When defining filters the WordPress documentation says:
“Filters are functions that WordPress passes data through, at certain points in execution, just before taking some action with the data (such as adding it to the database or sending it to the browser screen). Filters sit between the database and the browser (when WordPress is generating pages), and between the browser and the database (when WordPress is adding new posts and comments to the database); most input and output in WordPress passes through at least one filter. WordPress does some filtering by default, and your plugin can add its own filtering.”
So in a similar way to action hooks, filter hooks allow you to also execute your functions known as filters.
As we saw from the definition, the main purpose of a filter is to modify settings or text of various types before “adding it to the database or sending it to the browser screen”.
A filter hook can be identified by either of the following pieces of code:
  • apply_filters( $tag, $value );
  • apply_filters_ref_array( $tag, $args );
For example in the WordPress core you will find a line of code like the following:

$title = apply_filters('wp_title', $title, $sep, $seplocation);

The above example shows the creation of the wp_title filter hook. This hook allows you to manipulate a page’s title before it is displayed in the browser.
As for the action hooks, filter hooks follow a similar pattern. The $tag represents the name of the hook and there are also parameters which are passed to filters which are registered to the hook.
Unlike the do_action hook, the apply_filters hook will always pass a parameter to the filter (which is the customized function you write) and your filter in turn must always return the $value parameter back to WordPress.
To create and register a filter you will use a similar approach to creating an action. For example you will write a function (known as the filter) which does something and you will also register your filter to a particular hook using a command such as:

add_filter ( 'hook_name', 'your_filter', [priority], [accepted_args] );

where:
  • hook_name = name of the hook you want register to
  • your_filter = the name of your filter (or function)
  • priority = (optional) integer which represents the order your filter should be applied. If no value is added, it defaults to 10.
  • accepted_args = (optional) integer argument defining how many arguments your function can accept (default 1) because your filter must accpet at least one parameter which will be returned.
Let’s look at a simple example of creating and registering a filter.
The code below shows something you might add in your customized theme functions.php file to append the site name to a page’s title:

<?php

add_filter( ‘wp_title’, ‘mytest_add_sitename_to_title’, 10, 2 );
mytest_add_sitename_to_title( $title, $sep ) {
/* Retrieve site name. */
$name = get_bloginfo( ‘name’ );
/* Append site name to $title. */
$title .= $sep . ‘ ‘ . $name;
/* Return the title. */
return $title;
}
?>
We can see from this example that we are registering our filter which is called mytest_add_sitename_to_title to the wp_title filter hook and we are assigning a priority of 10 and specifying that our filter function will accept 2 arguments.
Also note that our filter returns the $title back to WordPress in order for it to be able to display the modified title to the screen.
In summary we’ve only just scratched the surface regarding hooks and their uses.
I hope that this introductory article has at least begun to demystify the subject of hooks and given you a small taste of what they are about and how you can identify and use them.
As always the WordPress codex and documentation pages are a very good place to start when you want to develop a deeper understanding of hooks.

No comments:

Post a Comment

Popular Articles