Write WordPress Code Snippets with fewer bugs: PHP Anonymous Functions

Founder of WPCodeBox

In this article, I want to show you how to reduce the number of bugs in your code snippets by using PHP Anonymous functions when adding WordPress actions or filters. 

So here is the "standard way" that most WordPress Code Snippets are written.

We add a function and then pass that function’s name as an argument to add_action, add_filter, and so on.

The problem with this is that the my_change_title function is global. This means this function exists alongside all the other functions defined by WordPress plugins, themes, or code snippets. And, if you use the same function name twice, you get an error.

A better solution is to use anonymous functions. To make this an anonymous function, we just need to remove the name and pass the whole function as an argument instead.

You can see the code is much cleaner now, and we have no risk of function names conflicting with each other. And, as the motto at the beginning said, we eliminate one of the most challenging things in computer science, which is naming things. We don’t have to come up with a unique name.

The only drawback is that you can’t remove actions programmatically with remove_action. But, from my experience, you rarely have to do this, if ever.

A lot of people still recommend going the named function route. However, the truth is, back in 2003, when WordPress launched, PHP didn’t support anonymous functions, so this was the only way of doing things, and people got used to it.  

But since 2009, when PHP 5.3 came out, anonymous functions have been supported. Also, for a long time, WordPress's minimum supported PHP version was 5.2, which cemented the notion not to use anonymous functions. But that’s not the case now when PHP 7 is required to run WordPress. 

The only time I think you might want to use named functions to allow users to remove actions and filters is when working on a huge plugin, like WooCommerce. So when writing code snippets or small plugins, we are safe.

From my experience in programming, we should always strive to prioritize clear, concise code over optimizations and “What-If” scenarios.


Customizing your WordPress site using 
Code Snippets is really easy.

Try WPCodeBox today. There's a 30-day money back guarantee.
Get WPCodeBox
Copyright © 2022 WPCodeBox SRL. All other trademarks are the property of their respective owners
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram