2

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 = '09112223344';
$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

3

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.

1
  • here is new problem with this change i want to call this function once, when new post publish but the function will be run multiple times.
    – Nadia
    Jun 8, 2019 at 7:16
2

To hook your method dothisfunction to action publish_post, you should use add_action() this way:

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

The number of arguments accepted by the function is specified in the 4th parameter of add_action().

However, this number can not be greater than the number of arguments passed in do_action(), because it is the do_action() that decides how many and what arguments will be passed to the functions hooked to specific action hook.

More about actions you can read here.

2
  • that's great but the problem is before new post , even if I just click the post the function trigger multiple times! i just want it to be run when i put a new post !
    – Nadia
    Jun 3, 2019 at 5:15
  • 1
    @Nadia You can use save_post (for any type) or save_post_{$post->post_type} hook (for specific post type) and check if $update argument is FALSE. add_action( 'save_post_POST_TYPE', array( $myClass, 'dothisfunction' ), 10, 4 );
    – nmr
    Jun 3, 2019 at 6:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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