Adding Arguments to WordPress Filters

a random assortment of wooden letter stamps

Introduction

This is a somewhat advanced article about WordPress filters. If you're not familiar with WordPress actions and filters, I suggest reading the WordPress plugin API documentation. It will help you get a start on what actions and filters do, how they're similar, and how they're different.

Yesterday, I ran into a situation I hadn't encountered before. We use Beaver Builder (BB from now one...) on many of our sites. I've also been working on a composer package of "theme helpers". Functions that we commonly use across our themes. I'm not sure if this is a good idea yet or not, but at least it could serve as a repository of snippets that people could use, include, adapt, or ignore as they like.

One of the functions I wanted to include would add UConn's brand font (Proxima Nova) to the list of fonts Beaver Builder supplies in text editors. Fortunately, BB has a filter called fl_builder_font_families_system that allows you to handle adding or removing system fonts from the list.

The pattern is basically

  • add the filter
  • use a callback to add your fonts to theirs
  • return all the fonts

This pattern works well if

  • you know in advance what fonts you want to add or
  • you're just using this pattern in one theme

But, in my case, I'm building a utility library. I can't know in advance which fonts might get used or how many there might be. That's going to be a bit of a problem.

The Problem

The callbacks to WordPress filters can't accept additional arguments using the pattern outlined above. For instance, the following won't work.

WordPress doesn't understand that I want fl_builder_font_families_system to suddenly start using two arguments instead of one. The signature for the filter says one argument and that's that right?

Well... not quite.

The Solution

Instead of dealing with the filter directly, we can use an anonymous function that returns another function as a closure. Now the pattern will be

  • add the filter
  • pass an anonymous function as the second argument adding our custom fonts with via the PHP use keyword
  • return a function that takes two arguments
  • that second function will combine all the fonts together and return them

This pattern is much more flexible! Now, I can add this pattern to the class in my library. That way, someone in the future could call the function as follows without ever needing to know the specific filter itself.

How? Well it's a matter of taking the two functions above, and combining them into a single class.

Conclusion

This is an extremely useful pattern to be aware of. With a closure, the WordPress filters can be much more flexible than they already are. It's a small thing, but in this case it allows us to continue building a library that can be used and maintained across many of our sites. I hope you enjoyed this post!

Posted by Adam Berkowitz