Friday, July 3, 2015

Wordpress: Introduction to hooks

What are wordpress hooks

Hooks are provided by WordPress to allow our plugin to 'hook into' the rest of WordPress; that is, to call functions in our plugin at specific times, and thereby set our plugin in motion. There are two types of hooks: Actions (Codex Action Reference) Filters (Codex Filter Reference)

Action Hooks

Action hooks are essentially placeholders. Wherever an action hook is placed, it will execute any code that has been "hooked" to it.

An example of this is the commonly used wp_head action hook, used by many themes and plugins to inject additional CSS stylesheets, processing code or anything else they require to sit between the <head> and </head> tags of their WordPress theme’s XHTML structure. This is the reason for including wp_head(); in all WordPress themes.

To hook on to an action, we create a function in our theme’s functions.php file (or in our plugin’s code) and hook it on using the add_action() function, as follows:

<?php
add_action( 'wp_head', 'wp_actionhook_example' );

function wp_actionhook_example () {

echo '<meta name="description" content="This is the meta description for this page." />' . "
";

}
?>


Filter Hooks

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.

Custom code is added as a filter using the add_filter() function. The following code adds a sign-off to the end of each blog post, only when viewing the full blog post screen:

<?php
add_filter( 'the_content', 'wp_filterhook_signoff' );

function wp_filterhook_signoff ( $content ) {

if ( is_single() ) {

$content .= '<div class="sign-off">Th-th-th-th-th That\'s all, folks!</div>' . "
";

} // End IF Statement

return $content;

}
?>
The above code adds a new div tag to the end of the content of our blog post, only when on a single blog post screen.

A filter hook is like using the str_replace() function in PHP. You give it some data, manipulate, replace or reformat the data and return the new content out at the end.

No comments:

Post a Comment