add_filter()
is a companion function to apply_filters()
. Before apply_filters
is run for a certain filter (the $tag
argument in add_filter()
), you can use add_filter
to register a filter for a tag. When apply_filters()
is executed with that tag name, it calls all the registered filters in order. Filters are used to pass data through functions for manipulation. For example, one that I often find myself using is the wp_list_pages filter. I use it to remove line breaks from the pages list. So here's how it works:
First I define a function that takes one parameter and returns it after working with it:
function my_list_pages_filter($pages){
$pages = preg_replace( array("\n","\r"), '', $pages );
return $pages;
}
Then I add the filter hook:
add_filter( 'wp_list_pages', 'my_list_pages_filter' );
add_filter
tells WordPress "When the function apply_filters
is called with the first argument being 'wp_list_pages', call my_list_pages_filter
." Filters must send at least one value (of any type: string, array, integer, etc.), and they expect the function to return one value.
They provide you a way to manipulate the input before sending it back.
do_action
is an entirely different hook. In order to send information to your filter function, do the following (taken from your example):
<div id="content" <?php $class='post post_content'; echo apply_filters('my_custom_classes', $class); ?>>
And then in your functions.php file, add this:
add_filter('my_custom_classes','my_custom_classes_function');
function my_custom_classes_function($classes){
$output 'class="'. $classes.'"';
return $output;
}
That's a pretty rudimentary use of filters, but it's a start. You can really get an idea of what you can do with filters with the same example with some enhancements:
function my_custom_classes_function($classes){
$classes = explode( ' ', $classes );
if(is_home())
$classes[] = 'home_content';
if(is_single())
$classes[] = 'single_content';
if(is_page())
$classes[] = 'page_content';
if(is_tag())
$classes[] = 'tag_content';
$output 'class="'. implode( ' ', $classes ) .'"';
return $output;
}