In our last lesson, we talked about action hooks. Now, we’re going to talk about how WordPress filter hooks work. Filter hooks, are the same as action hooks, except you’re passed a value and you must return a value.
WordPress Filter Hooks
You may want to modify certain content like the content, headers, titles, comments, etc. WordPress filter hooks are an excellent way to modify content. Just like action hooks, there are tons of WordPress filter hooks you can use. Click here for a list of them.
Once again, make a copy of your template folder and name it wpfilterex. Our index.php will look something like this.
* Plugin Name: WP Filter Hooks Example
* Plugin URI: http://jaskokoyn.com
* Description: A Basic WordPress Plugin to show how a filter hook works.
* Author: Jasko Koyn
* Version: 1.0
* Author URI: http://jaskokoyn.com
// Set up our WordPress Plugin
// Include or Require any files
// Action & Filter Hooks
Let’s take a look at how a filter hook is structured.
<?php add_filter( $tag, $function_to_add, $priority, $accepted_args ); ?>
Looks familiar right? Just like an action hook, we take the same procedure to execute a filter hook. There’s 4 parameters. The first one is what we want to hook into. The 2nd parameter is the function we want to call when this hook is triggered. The 3rd is priority. The 4th parameter tells how many arguments the function is going to take in. By default, the amount of accepted arguments is 1 because WordPress filter hooks passes at 1 least variable into our function. This variable is the content or information we’ll be filtering.
So, let’s add our first filter. to our plugin. Add this line of code under the Actions and hooks comment
add_filter( 'the_content', 'jk_modify_content' );
As you can see, this time we’re aiming to modify the content. the_content is a filter hook for the content of your posts and pages. We haven’t defined the jk_modify_content() function yet. Let’s do that right now. Under our includes, add this line of code and then create a file called func.inc.php in your inc folder
include( 'inc/func.inc.php' );
In our func.inc.php file add this bit of code.
$content .= "Visit my site http://jaskokoyn.com for more info!";
Now, let me explain what’s going on here. Our function jk_modify_content() is passed the content from the post. We can name this variable whatever we want, but for common sense reasons, we name it $content. Then, we append a little message saying “Visit my site http://jaskokoyn.com for more info!” and then return the $content variable. Once it’s returned, it’s outputted onto the page. Activate your plugin and try it for yourself!
The filter function was specifically made to modify/filter any content.
We’ve learned quite a bit. Now the big question is, when should you use filter hooks and action hooks? Which would be appropriate for a specific task? Well, to put it simply, it’s up to you. In our next lesson, I explain in more detail about when to use either one and their differences.