nonces in custom oop plugin

How to use the check_admin_referer method with oop?
If I use as it follows the function can not be called:

class MyClass{
    function __construct(){ 

        if( isset($_POST['my_nonce_field']) && check_admin_referer('my_nonce_action', 'my_nonce_field')){               
            $this->update_item();
        }

    }
}

$test = new MyClass();

Read More

The above leads to the following error message:

Call to undefined function check_admin_referer()

Related posts

Leave a Reply

1 comment

  1. check_admin_referer is a pluggable function which means it is defined after plugins are loaded so call your constructor or instantiate the object after or using plugins_loaded action hook.

    ex:

    class MyClass{
        function __construct(){ 
            if( isset($_POST['my_nonce_field']) && check_admin_referer('my_nonce_action', 'my_nonce_field'))
                $this->update_item();
        }
    }
    
    add_action('plugins_loaded','newobj');
    function newobj(){
        $myclass = new MyClass;
    }