argument

Most WordPress developers are familiar with using add_action, but as you may have discovered the information on passing arguments to your callback function is hard to find. After a couple of hours of Googling, throwing a hissy fit, and good old trial and error I found a working solution, so I thought I’d share.

The problem

I wanted to run a function on admin_init, which would need arguments passed as an array. Running the function is easy enough:

add_action( 'admin_init', 'my_function');

function my_function() {
//some code here
}

Add_action does accept a third parameter, but it’s not what I hoped it was. Instead it’s the number of arguments your function can accept. So how do you actually pass these arguments?

My solution

The answer appears to be using do_action, which is something I’d never personally worked with before, and using two functions. The first parameter of do_action is the hook name, followed by any arguments you want to pass.

add_action( 'admin_init', 'argument_function');

add_action( 'my_hook', 'my_function');

function my_function($argument) {
//some code here
}

function argument_function() {
$argument = 'something';
do_action('my hook', $argument);
}

Since I want to run my main function on admin_init, this is essentially a chain reaction.

The second add_action defines a custom hook, rather than one of the built-in WordPress ones, which I’m calling my_hook. On admin_init my argument_function is called, which passes the argument to my custom hook using do_action, which in turn triggers my_function but includes that argument.

If that last paragraph didn’t make your head explode, there’s one more thing to bear in mind. The third parameter of add_action is, as I mentioned, the number of accepted arguments. This defaults to 1, which is why it’s not needed in my example. If you’re passing more than one argument, you must be sure the number in that third parameter and the number of arguments being passed is the same, or the sky will fall down. No exaggeration.

There’s probably a better way to do this, but if so the documentation is scarce. It works, which is the main thing. If this helped you out, or if I’m doing it backwards, please leave a comment and let me know!

Found this post interesting, useful or at least vaguely intriguing? Consider getting future posts by RSS or email and you won't miss out on those awesome feelings ever again!