Using Filter Hooks

WordPress distinguishes action hooks from filter hooks. In this tutorial I want to take a closer look on filter hooks. In case you want to learn something about action hooks, check out the Using Theme Hooks Tutorial

What exactly are Filter Hooks?

Filter hooks are used to manipulate output. 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.

An example of this would be to add a line or text to the end of the content of each of your blog posts. Filter hooks can also be used for truncating text, changing formatting of content, or just about any other programming manipulation requirement.

The basic steps to adding your own filters to WordPress are:

  1. Create the PHP function that filters the data.
  2. Hook to the filter in WordPress, by calling add_filter()

Example:

The following code adds a text line to the end of each blog post, only when viewing the single blog post screen.

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

function themezee_filter_hook_example( $content ) {

	if ( is_single() ) {
		$content .= '<p>Example Text Line</p>';
	}
	return $content;
}
?>

 

You can find more information about action and filter hooks on these websites: