Do you want to change how WordPress shows a title, an excerpt or some text, without editing theme files? A filter hook is the right tool for that. It lets you take a piece of data, change it and hand it back to WordPress before it is used or displayed.
Understanding Filter Hooks
A filter is one of the two types of WordPress hooks. Before WordPress uses certain data, it passes that data through the apply_filters() function. Any function attached to that filter receives the value, can change it and must return it.
Think of it like the water filter in your kitchen. Water goes in, the filter changes it, and water comes out the other side.
A Filter Hook Example
By default, WordPress makes automatic excerpts 55 words long. Here is how you can shorten them to 30 words with the excerpt_length filter:
function wpt_short_excerpt( $length ) {
return 30;
}
add_filter( 'excerpt_length', 'wpt_short_excerpt' );
Your function receives the current value as $length and returns a new one. Like actions, filters accept a priority, which is 10 by default. Some themes set their own excerpt length, so you may need a higher number, like 99, so that your function runs last.
Popular Filters You Will Meet
the_contentchanges the post content before it is displayed.the_titlechanges post and page titles.excerpt_morechanges the text shown at the end of automatic excerpts.body_classadds extra CSS classes to the body tag of your pages.
WordPress uses filters itself too. For example, it hooks a function to comment_text that turns plain URLs in comments into clickable links. If you don't want that, see how to disable URL auto-linking in WordPress comments.
Always return a value from a filter function. If you forget the return line on a filter like the_content, your posts can show up completely empty.
Actions vs Filters
Here is an easy way to remember the difference. Actions do something, while filters change something. An action can run without returning anything, but a filter must always give the value back.
That's the filter hook in a nutshell. Once you write one or two, you will see how simple they are. Got a question? Ask it in the comment box below.