I wrote a quick set of helpers to assist in passing an anonymous function to multiple actions/filters as this has been an annoyance of mine since being introduced to anonymous functions and preferring them wherever possible. This is useful in scenarios such as wp_ajax
and wp_ajax_nopriv
.
Under the hood, add_action()
is simply a call to add_filter()
, so we are able to have add_actions()
call our new add_filters()
just as WordPress does in it’s core.
collect()
accepts an array or string, and if it receives a string, converts it to an array; so type checking our $filters
is not necessary.
helpers.php
/**
* Pass multiple filters to a callback.
*
* @param mixed $filters
* @param mixed $callback
* @param integer $priority
* @param integer $arguments
* @return true
*/
function add_filters($filters, $callback, $priority = 10, $arguments = 1)
{
collect($filters)->each(function ($filter, $index) use ($callback, $priority, $arguments) {
add_filter(
$filter,
$callback,
(int)is_array($priority) ? $priority[$index] : $priority,
(int)is_array($arguments) ? $arguments[$index] : $arguments
);
});
return true;
}
/**
* Pass multiple actions to a callback.
*
* @param mixed $actions
* @param mixed $callback
* @param integer $priority
* @param integer $arguments
* @return true
*/
function add_actions($actions, $callback, $priority = 10, $arguments = 1)
{
return add_filters($actions, $callback, $priority, $arguments);
}
Usage
// Simple Usage
add_filters(['wp_ajax_test', 'wp_ajax_test_nopriv'], function () {
wp_die();
});
// Passing multiple priority / argument values
add_filters(['wp_ajax_test', 'wp_ajax_test_nopriv'], function () {
wp_die();
}, [10, 12], [1, 2]);