How to use add_action to hook a static method from other Class

mark picture mark · Jan 31, 2017 · Viewed 8.5k times · Source

I tried to use hook to call a static method, but it failed.

I add the action in test.php like this

 require_once('class.test.php');
 add_action('register_new_user', array('Test','auto_signin'),20);

and my auto_signin function put in class.test.php file:

 namespace MyTest;
 echo(12);
 class Test {
    function __construct()
    {

    }

    public static function auto_signin()
    {
       echo('hello');
       die();
    }
  }

when I debuged it, the hook register_new_user did execute and from the global variable wp_filters, the auto_signin function had been added to register_new_user, but the function never executed.

Answer

Nathan Dawson picture Nathan Dawson · Jan 31, 2017

Your class, Test, is namespaced however you aren't using any namespace when calling add_action.

Update this:

add_action('register_new_user', array('Test','auto_signin'),20);

To this:

add_action( 'register_new_user', array( 'MyTest\Test', 'auto_signin' ), 20 );