【问题标题】:Wordpress - How to pass argument to add_action while the method is inside a class?Wordpress - 当方法在类中时如何将参数传递给 add_action?
【发布时间】:2019-08-23 02:53:44
【问题描述】:

在我的functions.php 我有

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

在我的MyClass 课程中,我有

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

但var_dump 的输出是string(0) ""。我想要的是将参数作为$type 传递给这个类。我尝试通过do_action 传递它,但我认为这不是最佳做法。

如何将参数传递给 add_action 的类中的方法?

【问题讨论】:

    标签: php wordpress class parameters arguments


    【解决方案1】:

    根据Wordpress Documentation:
    add_action 最多可以有 4 个参数,其中第四个是可传递给函数的参数数量。

    add_action( 'init', 'MyClass::make', 10 /*Action priority, default is 10*/, 1  );
    

    然后你可以将任何东西作为一个参数传递给函数:

    do_action( 'init', "Here I am!" );
    

    【讨论】:

    • 另外这个问题是“can I pass arguments to my function through add_action?”的副本。
    • 正如我所说,我使用了您提到的do_action!问题是当我这样做时,对于do_action('add_meta_boxes', 'my-post-type'),它返回Fatal error: Uncaught Error: Call to undefined function add_meta_box()。我认为是因为有两个do_actions,一个来自 wordpress,一个来自我的自定义代码,或者它可能比那个更早执行并返回此错误!
    • 根据您的评论,您得到的错误是因为函数add_meta_boxes 在被调用时不包括在内。同样在 PHP 中不可能有两个同名的函数。我建议您尝试打印一些堆栈跟踪并检查此错误的来源。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    • 2011-06-03
    • 2012-09-17
    • 1970-01-01
    • 2015-01-29
    • 1970-01-01
    相关资源
    最近更新 更多