Run Function After WordPress Plugin Activation

When you are creating a WordPress plugin there are some things you may need to do when the users activate a plugin.

For example if you need to setup a database for your plugin to run correctly you don't want to check if the database is setup everytime the plugin is ran. You want the database to be setup when the plugin is activated, that way you know that the database will be there when your plugin is running.

Plug In

There is a hook you can add to your plugin file which will run a function when the user activates it called register_activation_hook. To use this just add the following at the top of your plugin.

register_activation_hook( __FILE__, 'plugin_activated' );

This will then run the function plugin_activated when the user activates the plugin.

PHP Classes

If you work with PHP classes then you can place this hook outside of the class to call a method inside like this.

class MyClass
{
    public static function plugin_activated(){
         // This will run when the plugin is activated, setup the database
    }
}

register_activation_hook( __FILE__, array('MyClass', 'plugin_activated' );

If you have a function that runs on activating the plugin then you will need to clean up after yourself when the user deactivates the plugin, this is where you use the register_deactivation_hook, it works exactly the same as the activate hook but will run when you deactivate the plugin.

class MyClass
{
    public static function plugin_activated(){
         // This will run when the plugin is activated, setup the database
    }

    public static function plugin_deactivated(){
         // This will run when the plugin is deactivated, use to delete the database
    }
}

register_activation_hook( __FILE__, array('MyClass', 'plugin_activated' );
register_deactivation_hook( __FILE__, array('MyClass', 'plugin_deactivated' );

Constructor

You can even place this inside the constructor of the plugin by using this.

class MyClass
{
    public function __construct(){
         register_activation_hook( __FILE__, array($this, 'plugin_activated' );
         register_deactivation_hook( __FILE__, array($this, 'plugin_deactivated' );
    }

    public function plugin_activated(){
         // This will run when the plugin is activated, setup the database
    }

    public function plugin_deactivated(){
         // This will run when the plugin is deactivated, use to delete the database
    }
}

Advertise here

Comment