admin管理员组

文章数量:1434909

in my functions.php I have

require 'autoloader.php';
add_action('init', 'MyClass::make');

and in my MyClass class I have

class MyClass {
    public static function make($type) {
        var_dump($type);die;
    }
}

but the output of var_dump is string(0) "". What I want is to pass the argument to this class as $type. What I tried was to pass it through do_action however I think it is not best practice.

How can I pass argument to a method which is inside a class for add_action?

in my functions.php I have

require 'autoloader.php';
add_action('init', 'MyClass::make');

and in my MyClass class I have

class MyClass {
    public static function make($type) {
        var_dump($type);die;
    }
}

but the output of var_dump is string(0) "". What I want is to pass the argument to this class as $type. What I tried was to pass it through do_action however I think it is not best practice.

How can I pass argument to a method which is inside a class for add_action?

Share Improve this question edited Apr 2, 2019 at 5:32 fuxia 107k39 gold badges255 silver badges459 bronze badges asked Apr 1, 2019 at 21:03 AlexAlex 1
Add a comment  | 

2 Answers 2

Reset to default 1

Here's another example on how you could implement the add_action:

$type = 'my_sample_type';

add_action(
    'init',
    function() use ( $type ) {
        MyClass::make( $type );
    }
);

The init hook doesn't pass any parameters - when you call add_action, init isn't passing anything to make.

You could just call make outright:

require 'autoloader.php';
MyClass::make( <whatever );

If you need to do this on init, set up a callback function:


function add_my_type() {
    MyClass::make( <foo> );
}

add_action( 'init', 'add_my_type' );

本文标签: phpHow to pass argument to addaction while the method is inside a class