Use Filter Hooks in WordPress

In the previous article we looked through a common hook in WordPress is Action Hook. But besides Action Hook, we have another type of common Hook and it plays equally important roles in programming in WordPress, which is Filter Hook.

What is Filter Hook?

Filter Hook mean an anchor point is declared in the source WordPress plugin or theme so we can fix the PHP script at anchor point where it was declared.

How to use Filter Hook?

Hook Filter function is declared by apply_filters () like this (we're going to try with template footer.php):

$copyright = 'Copyright BRT 2015';
echo apply_filters( 'tut_copyrights', $copyright );

Like what you see, instead of echo $copyright variable out, I'll put this variable into apply_filter() function, which tut_copyrights is the name of the Filter hook.

Now, if I don't want to echo this fixed content, I can create a callback function then use add_filter() function to call it. So, I don't have to touch my code again - the value of $copyright will be given by another variable. Remember, this is not template tag should put in functions.php file.

function theme_copyright( $output ) {
$output = 'Wordpress powered';
return $output;
}
add_filter( 'tut_copyrights', 'theme_copyright' );

Now you can see, the 'Copyright BRT 2015' text has been replaced with 'Wordpress powered' by using filter.
When you declare any parameter in the callback function, Filter will automatically understands this is contained data function, and then in the function we assign it a new value and return that value back. Finally, we use add_filter() hook into the filter need to be changed.

Examples

Like Action Hook, WordPress has some pre-built Filter hooks those you can use. These are some most popular Filter hooks you have to know:

1. the_content

This Hook helps us filter the content that printed out. Let's try with str_replace() function to print bold a word:

[php]
function print_bold_letter( $content ) {
$find = 'Hello world';
$replacement = "hello";
$content = str_replace( $find, $replacement, $content );
return $content;
}
add_filter( 'the_content', 'print_bold_letter' );
[/php]

2. wp_handle_upload_prefilter

This Hook will be called out to filter file that was uploaded to Media Library. With this Hook, you can use $file parameter to rename file after uploaded to server.

[php]
add_filter('wp_handle_upload_prefilter', 'custom_upload_filter' );

function custom_upload_filter( $file ){
$file['name'] = 'wordpress-is-awesome-' . $file['name'];
return $file;
}
[/php]

Conclusion

Use Filter hook is pretty simple, so you should try and keep in mind few common Hooks of WordPress - it's very important with new WordPress developer. Otherwise, you can easily create a new hook to use in your specific purpose like use in your framework or plugin.