0

I am developing a WordPress plugin which requires certain rules to be added to the .htaccess file of the WordPress installation upon activation of the plugin.

Initially, before I switched my code to OOP (with classes and functions) the hooks and this functionality was working. But after I switched it, it doesn't work.

register_activation_hook( __FILE__, array( 'Optimizo', 'activation' ) );

The above code is how I am trying to call the function 'activation' from the class 'Optimizo' which resides in the same file as where I am writing the above activation hook. The 'activation' function has the necessary classes in it which should be called upon activation. Below is the content of the function.

protected function activation() {

    $this->activate();
}

I am just wondering if I wrote the code wrong of is it because that the function is having the protected access specifier or if I am doing something entirely wrong.

PS the function 'activate' resides in another class which is being extended to the 'Optimizo' class.

1 Answer 1

1

The function needs to be public, but it can also be static.

For example, from the Akismet plugin:

In the plugin file:

register_activation_hook( __FILE__, array( 'Akismet', 'plugin_activation' ) );

In the Akismet class file:

public static function plugin_activation() {
    ...
}
7
  • I tried changing the function to 'public' from 'protected', but now I am getting the following error when I try to activate my plugin. "Fatal error: Uncaught Error: Using $this when not in object context" Also the function now looks like: public function activation() { $this->activate(); }
    – Minhaz
    Commented May 14, 2019 at 14:11
  • And the activate function is also public public function activate() { ... }
    – Minhaz
    Commented May 14, 2019 at 14:12
  • @MinhazIrphan $this is not available inside the static method.
    – nmr
    Commented May 14, 2019 at 14:44
  • 1
    your callable references a static method, not a dynamic on, you would need to swap Optimizo for a variable instance of your class. Otherwise it would have to be static, and you'd need to change all the methods that function calls to static versions too
    – Tom J Nowell
    Commented May 14, 2019 at 15:22
  • 2
    Thank you very much for all the answers, as @TomJNowell said, I changed the activation hook from register_activation_hook( __FILE__, array( 'Optimizo', 'activation' ) ); to register_activation_hook( __FILE__, array( $optimizo, 'activation' ) ); And it seems to be working fine...
    – Minhaz
    Commented May 14, 2019 at 16:31

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.