This post looks at the hooks, actions, and filters that can be used to extend the code of a WordPress site.
While this article is targeted at WordPress developers, it does not hurt to learn the core concepts as a WordPress user.
To quote WordPress itself, "Hooks are a way for one piece of code to interact/modify another piece of code at specific, pre-defined spots."
They are an easy way to add functionality to your site without breaking WordPress updates. To use them you write a custom function known as a Callback, and then register it with a hook for a specific action or filter. Hooks 'hook' into core WordPress behavior.
They come in two types - actions and filters.
An action hook is technically a PHP do_action( ) function. An example is 'init' in the code block below.
You create custom action hooks by calling the do_action( ) function and passing in the your action hook name and custom function (βmy_user_checkβ below) with the code you want to run.
However, most of the time you will use established hooks in the WordPress core code or plugins. Here is the official WordPress Action Hooks reference.
Hooks have two available arguments: $tag (my_user_check below) and $arg.
Take a look at this simple example.
<?php
add_action( 'init', 'my_user_check' );
function my_user_check( ) {
if ( is_user_logged_in( ) ) {
//your code for do something if user is logged in
}
}
?>
Like action hooks you can tap into WordPress filters.
Rather than inserting your code where the hook or do_action ( ) exists, you are "filtering" the returned value of existing functions that use WordPress's apply_filters ( ) function.
You are filtering content before it's inserted into your site's database or before it's displayed in the browser as HTML.
For apply_filters( $tag, $value, $var );
Filters can be called from any theme or plugin.
Here is an example filter you could use to alter the title of any WordPress post returned to the browser.
<?php
add_filter( 'the_title', 'my_filtered_title', 10, 2 );
function my_filtered_title( $value, $id ) {
$value = '[' . $value . ']';
return $value;
}
?>
As a side note functions work the same way in both actions and filters.
What are common WordPress hooks?
As you have seen action hooks and filter hooks are a way of extending your sites functionality beyond the default code. You can use them in both themes and plugins.
Since this article was a quick and general overview of hooks, here are some useful resources with more extensive information.