Actually I’ve lost count of days because I decided to complete the chapter of Plugin Development first, and then revisit it to write these blogs so that I’ll be clearer on these topics.
I’ll start with day 5 and add one important topic each day. Today’s topics will be hooks, actions and filters.
Hooks are the mechanisms using which we can attach our piece of code to the wordpress core. By definition given in codex:
Hooks are a way for one piece of code to interact/modify another piece of code.
There are two types of hooks:
- Actions
- Filters
Actions:
Actions allow you to add data or change how WordPress operates. Callback functions for Actions will run at a specific point in in the execution of WordPress, and can perform some kind of a task, like echoing output to the user or inserting something into the database.
Add action:
<?php
function wporg_custom()
{
// do something
}
add_action('init', 'wporg_custom');
where ‘init’ is the hook i.e. the event at which ‘wporg_custom’ function will be executed.
Filters:
Filters give you the ability to change data during the execution of WordPress. Callback functions for Filters will accept a variable, modify it, and return it. They are meant to work in an isolated manner, and should never have side effects such as affecting global variables and output.
Add filter:
<?php
function wporg_filter_title($title)
{
return 'The ' . $title . ' was filtered';
}
add_filter('the_title', 'wporg_filter_title');
Adding custom hooks and filters is also possible. For full reference, refer to Hooks chapter in Codex.