4

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.

mark
  • 208
  • 1
  • 3
  • 11

3 Answers3

7

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 );
Nathan Dawson
  • 18,138
  • 3
  • 52
  • 58
  • @Popnoodles I don't believe that would be valid in this context. The question is about using a static method with add_action. If add_action was being called within the class, they'd be able to use ` __CLASS__` but the example provided shows it's from outside. – Nathan Dawson Oct 29 '20 at 16:28
  • ah, from 'other' class. ok – Popnoodles Nov 03 '20 at 16:29
1

The way you are trying will work when you want to attach object method to hook not the static method of the class. Since you want the static method of the class to attach to a hook, you need to add like below.

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

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

Note: if you want to hook from another file you need to add namespace too and call code like below

add_action('register_new_user', '\MyTest\Test::auto_signin',20);
Nabeel Perwaiz
  • 193
  • 1
  • 7
0

I read Wordpress Plugin API Reference, but I cannot find any action named register_new_user, so you must be using a custom hook.

However, the method will be executed if and only if it is hooked and this hook should a corresponding do_action hook.

See this code:

class PluginTest {
    function __construct(){
    }
    public static function insertNew(){
        echo 'Hi!';
        die();
    }
}

do_action('custom_admin_notices');

add_action( 'custom_admin_notices', array('PluginTest', 'insertNew'), 20);
global $wp_filter;
var_dump($wp_filter['custom_admin_notices']);

If the do_action line is commented, you can still see the hook in the global variable while the method won't be executed. So check whether the line containing do_action is executed.

Haotian Liu
  • 886
  • 5
  • 19
  • if I changed `add_action('register_new_user', array('Test','auto_signin'),20); ` to `add_action('register_new_user', function(do something);)` , the function will be executed. – mark Jan 31 '17 at 05:38