danirod

Lambda Functions and WordPress

Even if my personal website doesn’t use WordPress anymore, some of my projects, such as the backends for makigas.es, are still using WordPress. Since they are personal side-projects, I infinitely postponed fixing all the bugs on the template and plugin system, but this week I decided to take this seriously and finally make a nice webpage for my project.

One of the most common tasks in WordPress is setting up filters or actions. These are functions that are told to WordPress to execute during some events, such as when the plugins have been loaded, when the wp_head() function is executed… Traditionally you create a function with whatever you want your plugin or theme to do for you, and then you register a filter, usually by just calling add_filter or add_action passing the name of the function as a string argument, such as:

<?php
function my_plugin_register_settings() {
  do_something();
  do_something_else();
}
add_action( 'admin_init', 'my_plugin_register_settings' );

Some kind of voodoo witchcraft, or just reflection, will do the rest for you. However, it turns out that for a few PHP releases, even before PHP 7, there have been lambda functions as part of the programming language. And it turns out, that all these WordPress functions, are compatible with lambda functions.

So, if you feel uncomfortable polluting your global namespace with all these functions, even if they are prefixed, you can make your function a lambda function and pass it to add_action or similar functions:

<?php
add_action( 'admin_init', function() {
  do_something();
  do_something_else();
} );

Does this have any drawbacks? Well, it turns out that yes. WordPress official docs on add_filter state that if you plan to use your callback more than once, don’t use lambda functions, since PHP optimizers such as APC don’t cache them. Instead, create an actual function for that.

However, for small callbacks that are only intended to be executed once, such as registering widgets or registering custom post types, I find these lambda functions extremely useful and they avoid me having to create a real function.