WordPress Filters Fundamentals

Ok, so you’ve read my previous articles on PHP basics and how to use WordPress action hooks. Now you want to play with the big boys and girls and try your hand at filters. Just a reminder that you are still essentially learning a new language. Be patient with yourself. It took me close to a year to really understand filters, so if I can help you learn it quicker than that I’ll consider this a successful article.

In my discussion of hooks and functions I have described the system of hooks in WordPress as being similar to a parking lot. The hooks are like spaces, the cars are like functions that can be parked anywhere and can be moved around. To expound on this metaphor, (or to beat it to death) I think a filter is similar to changing something about the car while leaving it in the same place. A filter is like a magic function box that takes a value in ( remember I talked about parameters in by Basics tutorial ) do something with it and send it back. So you have a red Porsche on the lot, send it to a filter and it might become a blue Porsche. Or a black pickup truck. Whatever. But it will still be parked in the back, 2 spots from the end.

When browsing WordPress core, themes and plugins, you will be alerted to the availability of a filter by the appearance of the apply_filters() function. In generic terms it will look like so:

[php]
apply_filters( ‘name_of_target_filter’, $variable_getting_filtered, #priority, $other_arg );
[/php]

It might look like:
[php]
return apply_filters( ‘name_of_target_filter’, $variable_getting_filtered, #priority, $other_arg );
[/php]

or:
[php]
echo apply_filters( ‘name_of_target_filter’, $variable_getting_filtered, #priority, $other_arg );
[/php]

or even:
[php]
$variable_getting_filtered = apply_filters( ‘name_of_target_filter’, $variable_getting_filtered, #priority, $other_arg );
[/php]

Parameters for the Filters

But I repeat, the big tip off is the apply_filters() function. The apply_filters() function can take an unlimited number of parameters but only the first two are required.

1. The first is the name of the filter. I was very confused early on because the Thematic framework tended to name the filters the same thing as the functions that contained them. And then in the one instance where they were different, I couldn’t get my filter to work for anything. I swore and threw things, cried and probably shaved a few days off my life from the stress. Turns out their sharing names was a convenience factor that makes a lot more sense to me now. So, just remember that first parameter is the filter’s name.

2. This is an important one, because this parameter is the variable that your function will receive. This is the value we’re going to change. This is the red car that we will turn blue.

3. This it the priority. Just like with adding functions to hooks, this controls the order that filter functions will be applied should there be more than one. The default is 10, so if you need your filter to run before that you’d use a lower number. This is rare, and usually you need to run your filters after others, so you’d want to use a higher number. In fact, until you are sure that you are conflicting with another function you can pretty much just leave it at 10.

4+. These are other variables that might give you some useful information for manipulating the variable getting filtered. Remember we talked about scope in the PHP Basics. Instead of declaring these globally and hoping they arrive intact, WordPress will send your filtered variable along with some friends.

A Filter with Training Wheels

In super generic terms let’s take a look at the basic set up for filtering.
[php]
function sample_filter_function( $in_from_function, $other_arg ) {
$out_to_function = $in_from_function . " add some bacon here!";
return $out_to_function;
}
add_filter(‘name_of_target_filter’,’sample_filter_function’, #priority, 2 );
[/php]
The structure is almost exactly the same as that for add_action(). In reality, we are adding an action, just of a slightly different type: one that modifies a specific variable’s value. One thing to note here, is the number 2. This is the number of parameters that you are passing into the function. You’ll always pass 1 variable ( ie. the variable that you are filtering ) and in this case you wouldn’t even need to declare it. That’s the default value, just as 10 is the default value for #priority. However, some filters provide access to other variables (like our fake $other_arg), and if you want to use them in your filter function then you have to name them inside the parentheses and then write the correct number at the end of the add_filter() statement.

If you have 2 parameters in the function, but don’t have the number 2 at the end of add_filter() you will get White Screen of Death. If you have the number 2, but don’t declare two parameters, guess what, you will also get WSOD. So make sure your parameters match up.

And you absolutely, must, sans doute, return a value. If you do not, that is essentially the same as returning a null string. If you echo something here, it will likely not appear where you expect it, so don’t. RETURN, RETURN, RETURN. Remember in my PHP basics I talked about two functions playing catch. The return statement, is you throwing your modified version of the variable back to the apply_filters() function so that WordPress can continue on its merry way, but using your value now.

You’re a Real Boy Now, Pinnochio. A Real Filter

If you’ve managed to read all this, then… well… Bless you. I want to end on a real filter that you can drop into your theme’s functions.php and actually see a working result.

[php]
function kia_the_title( $title ) {
$title .= " BACON!";
return $title;
}
add_filter(‘the_title’,’kia_the_title’ );
[/php]

Not too shockingly I am using Bacon in my testing code. If this bothers you…. well, its just code and not real bacon. WordPress has a filter called the_title() that lets you modify the title of every post! As written above it will literally add BACON everywhere the_title() is called. Bacon everywhere, all the time has its appeal, sure, but I will whet your appetite with some neato WordPress conditional logic that will only add Bacon to the titles in the main loop, and only on the front-end.

[php]
function kia_the_title( $title ) {
if ( ! is_admin() && is_main_loop() ) {
$title .= " BACON!";
}
return $title;
}
add_filter(‘the_title’,’kia_the_title’ );
[/php]

Conclusion

I hope that helps things make more sense. Remember, THIS IS HARD!! Do not be discouraged if you don’t get it right away. I cannot provide specific support in the comments ( Hire Me, instead! ) but do let me know if there are places where I could be more clear.

View all posts in this series
This entry was posted in Understanding the Basics. Bookmark the permalink. Trackbacks are closed, but you can post a comment.

14 Comments

  1. Posted October 20, 2012 at 9:24 pm | Permalink

    Hi Kathy –

    Great article, and good to see you helping out a bit more in the forums. Just linked to this article here: http://thematicmondo.com/directory/resources-tutorials/

    Scott

    • Posted October 21, 2012 at 1:13 am | Permalink

      i wouldn’t call self-promoting really “helping out”, but i always meant to write/share this. it just took getting stuck on the train with no wifi for it to happen.

  2. Posted October 21, 2012 at 12:42 pm | Permalink

    Fantastic to see the documentation for Thematic growing. Well done on writing a crucial, educational and fun tutorial. Thanks as well for your commitment to the Thematic support forums.

    • Posted October 21, 2012 at 1:32 pm | Permalink

      hi dominor! glad you liked the tutorial. Filters go way beyond Thematic (though that is where I learned them) and are powerful for dealing with all themes, plugins and the WP core!

      • Posted October 21, 2012 at 1:50 pm | Permalink

        Funny you should say that. My modest schooling in filters/hooks is a direct result of using Thematic too. Little did I know that by learning Thematic’s filters/hooks I was inadvertently being equipped with the essential know-how for writing plugins. Even though to date, I’ve never actually authored a plugin, this was mind-blowing to me at the time because I had always viewed plugin authoring as a more expert and probably unobtainable tier of WordPress knowledge. Thematic has also introduced me to the intelligent practice of child themes vs. core hacking. I don’t think I’d have learned all of these concepts as quickly/fully as I would have had I had opted for building custom themes from scratch without a theme framework like Thematic. There’s a lot to be said about how much the novice can learn from digging into Thematic or merely using it.

        • Posted October 21, 2012 at 1:55 pm | Permalink

          Plugin authorship is not unobtainable! I went from not knowing any of this and now I have a few plugins in the WordPress repo. In fact, I find myself doing more development than design these days. But totally agree, I learned a ton from digging around in Thematic.

  3. Diallo
    Posted May 17, 2013 at 1:52 pm | Permalink

    very clear !!!
    thank you for your help

    Kathy is Awesome…. that’s right!!!!!

  4. Posted December 23, 2013 at 4:50 am | Permalink

    Thank you very much,
    Just I don’t know why my `apply filter` broke the code
    I have a custom home page `home.php`
    I’m trying to do

    $the_content = get_the_content();
    apply_filter('the_content',$the_content);

    the page stop loading after that point of code

    • Posted December 23, 2013 at 5:31 am | Permalink

      Turn on debugging so that you will know what is causing your problems. In your case, you have an obvious typo. apply_filter isn’t a function…. but apply_filters is. Also, why not just use the_content() in lieu of getting the content and then applying filters.

  5. Cy
    Posted February 12, 2014 at 12:02 am | Permalink

    Your articles are so well written that I found myself reading three (3!) PHP tutorials in a row. I am a beginner, but today less, thanks to you. I find these really helpful guides funny and unique. Did you consider publishing a book to help people to learn such things?

    If you write one about woocommerce, I am sure you wont need anybody else to hire you ever again. Just sayin’..

    All the best.

    • Posted February 12, 2014 at 12:25 pm | Permalink

      Aww shucks. Thanks for the lovely compliments. I probably won’t be writing a book, but I probably should do more writing. If I were going to write about WooCommerce what would you want to read?

      • Cy
        Posted February 19, 2014 at 12:06 pm | Permalink

        Sorry I just saw this, and funny though, I have seen your profile many times while going through different forums (specially wordpress.stackexchange) trying to understand more. Every time you posted an answer, it was truly helpful, so thanks again (the instruction on how to add category to single posts saved many hours of my day :)

        Coming back to your question, I think what’s needed in Woocommerce is some sort of guide that shows the way for newbies. WC seems to be coded for PHP pros and, either you use WC as it is with all their shortcodes and widgets, or you spend months and days understanding their templates and functions (and learning a lot of PHP on the way) to start creating something customized. There’s no point in between. Either you use it how it is or you spend months learning. And if you want to move forward learning on your own, there is no guide whatsoever, its really easy to get discouraged.

        What’s missing is exactly what you started to do in these three posts, and then, going deeper. I dont want to hire a developer for two or three fixes because I want to have the knowledge too. I would pay for learning it easily, and I am sure many more people would do.

  6. c0p
    Posted May 4, 2014 at 2:40 am | Permalink

    Kathy,
    Great page! I visited here a few months ago and am revisiting to update some other code I’m working on. The problem here is that this pages code blocks styling seem to be having a problem. It all looks like white boxes to me. I am using a couple different versions of Firefox and have tried in Google Chrome but the code blocks are unreadable. Your latest posts seem to look fine but those created within this time period are broken. Please correct this. I can edit the css and see the code but many people may not be able to do this.

    Again, great tutorials here. You really do have a knack for explaining this stuff well.

    Corey…

    • Posted May 5, 2014 at 2:29 pm | Permalink

      I guess that’s what I get for trying to slowly tweak my website’s design. Thanks for the heads up. I will eventually make my way through the posts and fix all the markup, but I’ve added some CSS that should take care of it in the meantime.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

You may use markdown syntax in the comments.

This site's anti-spam requires Javascript; enable it and refresh this page to continue.

NoScript Users: Whitelist the domain services.wpspamhammer.com and refresh.