为什么 add_action 仅适用于 functions.php 而不是插件?

Pod*_*eEu 2 php wordpress plugins woocommerce

当我把我的代码 functions.php

从...开始

add_action( 'woocommerce_order_status_completed', 'do_something' );
here is my code
Run Code Online (Sandbox Code Playgroud)

有用!但是当我把它放进去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();
    }
}
Run Code Online (Sandbox Code Playgroud)

这不起作用。为什么?

Lee*_*Lee 5

这是通过删除代码位和对删除键的过度热情导致非常重要的信息丢失的情况之一。

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

尝试:

add_action( 'woocommerce_order_status_completed', array(&$this, 'do_something') );
Run Code Online (Sandbox Code Playgroud)