Before continuing adding features to our WordPress plugin, we need to know what hooks, actions and filters are.
What does WordPress say?
“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.”
So, basically hooks, will let you modify content, add features, and much more, without touching anything of the WordPress Core.
There are two types of hooks:
- Actions: This kind of hooks are launched by the WordPress Core at specifics points during execution, or when specific events occur. Like publishing a post, changing themes and so on.
- Filters: They will let you to modify content on the fly. You can, for instance, modify a post content before it is shown to the user or just doing the opposite like modifying some user content before saving it to the database.
Let see some examples to truly understand the magic of hooks!
Filter hooks
function set_default_content($content) {
$default_post_content = "This is our default post text!!";
if (!isset($content) || trim($content)=='')
return $default_post_content;
return $content;}
add_filter("the_content", "set_default_content");
There are a lot of filter hooks available via the WordPress API. For a full list check out the WordPress API codex: http://codex.wordpress.org/Plugin_API/Filter_Reference
Also, you can see the default filters by opening up this file in your own WordPress installation: mywordpress/wp-includes/default-filters.php
To demonstrate the concept, let’s do a simple trick: change the color of the site title text. Our function, nothing special, will just print/echo some simple css rules.
function change_title_color() {
echo '
';
}
And here is the magic!
add_action('wp_head', 'change_title_color');
Take a look to the result
As you can see, I used the “wp_head” action hook. If you check your template header.php file, you can easily see when this hook will be called – I’ll give you a clue with the screenshot below:
Removing Actions and Filters
Importantly, WordPress gives you the chance to remove actions and filters. Why? Because remember that any plugin can add action and filter hooks, and some time you need to replace them or just remove because they are interfering with your owns functions.
So, to do this, you just need to call
remove_filter('filter_hook','filter_function')
remove_action('action_hook','action_function')
You can download the code dinkum-default-empty-post-content, and also there is a really good hook database here.
That’s all folks!