One of the most interesting features of the WordPress platform is the Hook capability, which can be easily used to any developer in order to add new features to themes and plugin. There are two distinct types of Hooks: Actions and Filters.
For a complete guide to Hooks you can read the official documentation available through the WordPress Codex (be sure to check the Actions and Filters specific sections): in this post we'll just say that Actions are general-purpose functions which can be triggered by the execution of some theme or plugin events, while Filters are functions accepting a source content and returning a result which will be used instead.
This is an example of a simple Action who can be used to send an e-mail to a predefined list of accounts whenever a new post is added to the blog:
1 2 3 4 5 6 7 8 |
class emailer { static function send($post_ID) { mail($addresses,"Hey! There's a new post on my blog!",'Hello, I just want to let you know that there is new stuff on my blog: http://blog.example.com'); return $post_ID; } } add_action('publish_post', array('emailer', 'send')); |
This is an example of a Filter who will look for profanity into the text field of each post replacing them with the #?*! string:
1 2 3 4 5 6 |
function filter_profanity( $content ) { $profanities = array('a bad word','another bad word','yet another bad word'); $content = str_ireplace( $profanities, '#?*!', $content ); return $content; } add_filter( 'comment_text', 'filter_profanity' ); |
Now that we know what Action e Filter are, we can see how we can add them to our WordPress site or blog.
The easiest (and fastest) way is to simply append them to the functions.php file of the currently installed theme: this task can be easily done by using the WordPress Administration panel (Appearance -> Theme -> Editor). It's as simple as opening the file using the WordPress editing interface and add the code of the desired Action or Filter after everything else. Despite its simplicity, this isn't always the best thing to do: any Action or Filter added this way will be lost as soon as you upgrade the installed theme.
That's why we suggest to adopt a more effective mechanism using an Hook management plugin like Add Actions and Filters, so you can insert your custom code in a separated container preserving it from theme changes and updates.
This is a screenshot of the aforementioned Add Actions and Filters plugin. Happy customization!
One Comment on “Adding custom Actions and Filters to your WordPress blog”