为什么add_action只能在functions.php中工作,而不能在插件中工作


Why add_action works only from functions.php not plugin?

当我将代码放入functions.php

从开始

add_action( 'woocommerce_order_status_completed', 'do_something' );
here is my code

它有效!但当我把它放在plugin 中时

if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
    if ( ! class_exists( 'WC_Some_class' ) ) {
    class  WC_Some_class {
            public function __construct() {
            add_action( 'woocommerce_order_status_completed', 'do_something' );
}
script ...
}
}
// finally instantiate our plugin class and add it to the set of globals
        $WC_Some_class = new WC_Some_class();
    }
}

这不起作用。为什么?

这是其中一个例子,通过删除代码中的一些部分并对delete键过于热情,导致了相当重要的信息丢失。

然而,我会在黑暗中试探一下,假设您正在将函数从functions.php移到类中。因此,add_action必须知道它需要调用类的函数(方法),而不是全局定义的函数。

尝试:

add_action( 'woocommerce_order_status_completed', array(&$this, 'do_something') );