Activation and deactivation within a class in WordPress plugin


When classes are used for developing WordPress plugins, the action and filter hooks are declared inside the class and they call class methods. So, you assume that activation and deactivation hooks will work the same way but they don’t. After searching and testing, there are two found solutions:

  1. Declare the activation or deactivation function outside of the class as well as the function to be executed. Look at this example:
    <code lang="php">
    class btClass {

    function __construct(){
    $this->setup_actions();
    }

    function setup_actions(){
    add_action(‘init’,array(&$this,’init’));
    }

    function init(){
    // do something
    }
    }

    $btClassPlugin = new btClass();
    register_activation_hook(__FILE__, array(‘btClass’,’bt_activate’));
    register_deactivation_hook(__FILE__, array(‘btClass’,’bt_deactivate’));

    function bt_activate(){
    // do something
    }

    function bt_deactivate(){
    // do something.
    }

  2. Declare the activation or deactivation function outside of the class and call the class method to be executed. Look at this example:
    <code lang="php">
    class btClass {

    function __construct(){
    $this->setup_actions();
    }

    function setup_actions(){
    add_action(‘init’,array(&$this,’init’));
    }

    function activate(){
    // do something
    }

    function init(){
    // do something
    }

    function deactivate(){
    // do something
    }
    }

    $btClassPlugin = new btClass();
    register_activation_hook(__FILE__, array(‘btClass’,’activate’));
    register_deactivation_hook(__FILE__, array(‘btClass’,’deactivate’));

Note: Uninstall hook has to be used the same as activation and deactivation hooks.

About Boronia Technologies

Boronia Technologies is the business name of Catherine Lebastard, an IT professional with extensive experience in web development and database administration. Catherine chose the name of Boronia as she likes flowers and purple color. The logo of her business is inspired on Boronia flower plus digital elements incorated inside the flower.


Why you should use my services?

Because I can guide you to the right path and provide you what you are looking for at the right price according to your budget. Also, I am able to develop or debug an application with any programming language that you request because I have the ability to learn at extremely fast pace and adapt easily to progress in technology.