Activation and deactivation within a class in WordPress plugin

[jamiesocial]

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 Me

Catherine Lebastard is a results-oriented professional with experience in web development, app development, and database design, analysis and administration. Bachelor degree in Computer Science and certified in Media Design and Web Development. Fluent in English and Spanish.


My skills

LANGUAGES: Visual.Net(C#,VB), Java, PHP, Python, HTML5, JavaScript, CSS3.
FRAMEWORKS: Django, Bootstrap, AngularJS
LIBRARIES: jQuery, Bootstrap
DATA VISUALIZATION: D3, NVD3, Tableau
CMS: Wordpress
ECOMMERCE: Shopify
DATABASES: Oracle, MS SQL Server, MySQL