I have a test.php plugin file inside my plugin/ folder and I am trying to send an email from this plugin.

I have a code that looks like this currently in my plugin.

   add_action('init', 'email_notifier', 10, 5);

   function email_notifier($type, $email, $subject, $body, $link){
    // wp_mail(....)

However it seems there is no way to pass outside variables to the email_notifier function.

I can send an email like this

add_action( 'init', 'email_notifier', 10, 2);
function email_notifier() {
   // wp_mail( '[email protected]', 'subject', 'content' );

But this limits me from dynamically setting and passing the email/subject/content to the function.

Is there any workaround for this


1 Answer 1


Take a look into this example:

add_filter('some_hook', $callback = function( $arg ) use ( $values ){
    //Some calculation here

You can set arguments this way, and also use the predefined variables that exist outside the functions scope, by using the use() term.

This way, you can unhook the function wherever you want, by doing this:

remove_filter('some_hook', $callback);
  • 1
    nice touch with the callback variable but IMHO with you going that way it is better to do the dynamic function creation outside of the add_filter itself, and obviously make the $callback an object property or global. just my 2 cents May 31, 2017 at 19:33
  • @MarkKaplun Thanks that'll work too. This was actually in one of the answers to my own question, which had 3 methods, including this, yours, and using global variables.
    – Johansson
    May 31, 2017 at 19:37
  • Thanks for this. I am assuming somehook is init?
    – meskerem
    May 31, 2017 at 19:51
  • @meskerem You are welcome. It can be any action or hook. I just left it that way so you can replace it with whatever you wish.
    – Johansson
    May 31, 2017 at 19:58
  • This function works if I use on the global scope. If I am using it in a function called ex: foobar then the email is not sent. Do you have any idea why?
    – meskerem
    Jun 1, 2017 at 12:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.