how can I use add_action with external class which the function contain 2 argument?

I create a file name custom.php which is like below:

class customClass{ 
   function dothisfunction( $mobiles , $message ){
      //use parameters
   }
 }

In my function.php file I add the following code:

$number="09112443986";
$mymsg = 'nadia is testing';
$myClass = new customClass();
add_action( 'publish_post', array( $myClass ,'dothisfunction', $number, $mymsg ) );

but it returns error, the error is :

PHP Warning: call_user_func_array() expects parameter 1 to be a valid callback, array must have exactly two members in C:\xampp\htdocs\wp-includes\class-wp-hook.php on line 288

How can I solve it? Can anyone help me?

2 Answers
2

The publish_post post takes two arguments first is $ID of the post that is being published and the second is the $post instance (See codex). I modified your code a bit below.

Your class is almost identical just renamed the parameters of the function to not cause confusion.

class customClass{ 
   function dothisfunction( $ID, $post ){
      echo "something";
   }
 }

No need for the $number and $mymsg in the array() because you only need to specify instance and the method to be used of the instance.

$myClass = new customClass();
add_action( 'publish_post', array( $myClass ,'dothisfunction' ), 10, 2 );

Also, you should specify how much parameters you are passing to dothisfunction in add_action as 4th parameter.

Leave a Comment