WordPress Filters Example for Beginners

WordPress comes with a lot of built in amazingness, one of those are filters. You can filter a lot of different things that WordPress outputs into your theme or from your plugin that originate from another place.

That means you can add or remove something to all titles, category names or widgets. That might not seem incredibly useful at first, but if you for example want to add a text at the end of a blog post or page while using an already existing theme, it can be very nifty.

Adding a filter can be done in your function.php in your child theme (or current theme) and you'll have to define a hook and a function.

The hooks are a list of points in the order of WordPress executing itself when a page is displayed.

You could say that it first:

  1. reads the config
  2. gets content from the database
  3. renders theme files

and so on. Honestly, that list is a bit longer and more complex. A complete list is available here: adambrown.info/p/wp_hooks/version/4.4.

Let's go ahead and create a filter that adds a little thank you note to blog posts that a user has read:

// the filter, first we specify "when" and then "what" is going to happen
add_filter( 'the_content', 'end_thanks' );

// $content, is your post content
function end_thanks( $content ){
    if( is_single() ){
    $content .= '<div id="thanks">
      <p>Thank you for reading! I\'d be happy if you would leave a comment and tell me what you think about it!</p>
        </div>';
    }
    return $content;
}

Let's have a look at what this code does line by line:

  1. add_filter specifies when to run what. The what has to be specified as the string of the function name
  2. end_thanks takes one parameter, $content which is the content of your post
  3. if (is_single()) checks if the $content we're filtering is a single (blog) post
  4. $content .= will add to $content at the end, also called append
  5. return $content; throws the changed (or unchanged) string back to the rest of the WordPress processing

WordPress Filter Order

If you want to run two filters on the same hook, you can change their order with the third parameter to the add_filter function like so:

add_filter( 'the_content', [$this, 'inject_container'], 30 );

Summary

That's the 5 minute introduction to WordPress Filters, I hope you enjoyed it!

Let me know what you are doing with filters or if you have created a theme! I'd love to see it!

Tagged with: #WordPress

Thank you for reading! If you have any comments, additions or questions, please tweet or toot them at me!