What is: Filter
In WordPress, filters are functions that can be hooked to an event (called hooks). During the execution when the event is triggered the filter is applied to the data output generated by the event hook. It is important to remember that filters perform their actions on data they receive and then return that data before it is displayed in the browser. Filters always have to have data coming in and data going out to ensure the data is output in the browser (your content may be passed through other filters before getting output in the browser). By comparison, actions, which are similar to filters, do not require that anything be returned, although data can be returned through actions as well.
Example: Let’s say we want to display an image icon when a post belongs to a particular category. In this scenario we create a function which checks if a post is in that particular category, if so, then display the image. Next, we hook that function into the_content
event. Now whenever the event the_content takes place, our functional is automatically triggered to filter the output.
// First we hook our own function with the_content event add_filter( 'the_content', 'wpb_content_filter' ); // Now we define what our function would do. // In this example it displays an image if a post is in news category. function wpb_content_filter( $content ) { if ( in_category('news') ) $content = sprintf('<img class="news-icon" src="%s/images/news_icon.png" alt="News icon" title="" />%s', get_bloginfo( 'stylesheet_directory' ), $content); // Returns the content. return $content; }
Additional Reading
- Action