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:

apply_filters( 'name_of_target_filter', $variable_getting_filtered, #priority, $other_arg ); 
Code language: PHP (php)

It might look like:

return apply_filters( 'name_of_target_filter', $variable_getting_filtered, #priority, $other_arg ); 
Code language: PHP (php)

or:

echo apply_filters( 'name_of_target_filter', $variable_getting_filtered, #priority, $other_arg ); 
Code language: PHP (php)

or even:

$variable_getting_filtered = apply_filters( 'name_of_target_filter', $variable_getting_filtered, #priority, $other_arg ); 
Code language: PHP (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.

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 ); 
Code language: PHP (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, Pinocchio.

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.

function kia_the_title( $title ) { 
    $title .= " TACOS!"; 
    return $title; 
} 
add_filter( 'the_title', 'kia_the_title' ); 
Code language: PHP (php)

I am using Tacos in my testing code because tacos are delicious. WordPress has a filter called the_title that lets you modify the title of every post! As written above it will literally add TACOS everywhere the_title() is called. Tacos everywhere, all the time has its appeal, sure, but I will whet your appetite with some neato WordPress conditional logic that will only add Tacos to the titles in the main loop, and only on the front-end.

function kia_the_title( $title ) { 
    if ( ! is_admin() && is_main_loop() ) { 
        $title .= " TACOS!"; 
    } 
    return $title; 
} 
add_filter( 'the_title','kia_the_title' );
Code language: PHP (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.

20 thoughts on “WordPress Filters Fundamentals

    1. kathy Post author

      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.

  1. Dominor Novus

    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.

    1. kathy Post author

      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!

      1. Dominor Novus

        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.

        1. kathy Post author

          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.

  2. foodonia.com

    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

    1. kathy Post author

      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.

  3. Cy

    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.

    1. kathy Post author

      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?

      1. Cy

        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.

  4. c0p

    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…

    1. kathy Post author

      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.

  5. Lucky Lam

    Hello Kathy, you’re awesome, really. Thanks for what you’ve done, they are useful. By the way, Could you suggest me any book that good to read about WordPress world ? :) Thanks in advance!
    – From Lucky with love

    1. kathy Post author

      Thanks Lucky. I’m glad you are enjoying my posts. I have never read any books on WordPress, so I wouldn’t feel right recommending one. If you are looking for more reading I would suggest reading everything you can at https://pippinsplugins.com/. Pippin has a lot of great info available.

      1. Lucky Lam

        Thank you Kathy. Have you ever thought about writing a wordpress book someday? I bet It’s gonna be a good one

        1. kathy Post author

          Lol… that sounds like way too much work for me. :) I can barely keep this blog reasonably updated… and by barely I mean I post once every few months! Anyway, I kind of think books are unnecessary for a subject such as WordPress. There is so much online (perhaps too much at times) but it is evolving so quickly that by the time a book might be ready it could be out of date.

Comments are closed.