6

i have sample wordpress plugin class. Im hooking woocommerce woocommerce_saved_order_items and i want create a admin notice. Add action from __construct works, but when i want create a notice in hook function it doesnt appears, where is the problem?

 class SomeClass {

        private static $instance;


        public function __construct() {
            add_action('woocommerce_saved_order_items',array($this,'orderStatusChange'),10,1);
            add_action('admin_notices', array($this,'simple_notice')); // This works
        }

        public static function getInstance() {
            if(!self::$instance)
                self::$instance = new SomeClass();

            return self::$instance;
        }


        public function orderStatusChange($orderID){
            add_action('admin_notices', 'simple_notice');//This not works
        }



        function simple_notice(){
            ?>
            <div class="updated notice is-dismissible">
                <p>Thank you for using this plugin! <strong>You are awesome</strong>.</p>
            </div>
            <?php
        }

    }


    SomeClass::getInstance();
1
  • 1
    Are you found any solution about this? I have the same problem!
    – Sangar82
    Commented Aug 28, 2017 at 10:46

1 Answer 1

1

Your problem is pretty simple. Your callback for this hook is not a simple function but some method of a class.

If you add action like this:

add_action('admin_notices', 'simple_notice');

you tell WP that there is some simple function called simple_notice and it should be called when hook admin_notices is processed. But... There is no such function anywhere in your code.

The function you want to call is method in your class, so you have to pass not only the name of function, but also object of given class, so WP is able to call this method. (And you've done it correctly in __construct).

This line works

add_action('admin_notices', array($this, 'simple_notice')); // This works

because the method is passed with full details - as an array describing object and it's method to call.

3
  • This is not working for me.
    – Radmation
    Commented Jul 26, 2018 at 22:18
  • @Radmation This is answer to the question “why my code doesn’t work”, not general tutorial “how to create notices”. So yeah - most probably it won’t work in your case, unless you have the same code as OP. Commented Jul 27, 2018 at 2:31
  • Well my code is built similar. I figured out a solution for my case however :D. What I was doing was posting data the non-ajax way and in my post handler I was wanting to set admin notices up. I ended up using the wp_options table to persist the "notice" between redirects..
    – Radmation
    Commented Aug 8, 2018 at 20:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.