简体   繁体   中英

Why add_action works only from functions.php not plugin?

When I put my code to functions.php

starting with

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

It Works! But when I put it in 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();
    }
}

This does not work. Why is it?

This is one of those instances where by removing bits of your code and being a little over enthusiastic with the delete key, has led to pretty important information being lost.

However i'll take a stab in the dark and presume you're moving the function from functions.php INTO the class. Therefore your add_action has to know that it needs to call the function (method) of a class, NOT a globally defined function.

Try:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM