Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding code to plugin that only executes the first time its activated?

Is it possible to wrap code in a special function that only executes the first time the plugin is activated?

I have some database code I need to run on plugin activation, but the code need not run again after that.

like image 453
Scott B Avatar asked Apr 22 '10 19:04

Scott B


2 Answers

Yes, this is possible. You can register a plugin activation hook that only gets run when the plugin gets activated. I dredged up an old plugin I wrote for some example code:

class MyPlugin
{
    //constructor for MyPlugin object
    function MyPlugin() {
        register_activation_hook(__FILE__,array(&$this, 'activate'));
    }

    function activate()
    {
        //initialize some stored plugin stuff
        if (get_option('myplugin_data_1') == '') {
            update_option('myplugin_data_1',array());
        }
        update_option('myplugin_activated',time());
        //etc
     }
}
like image 71
zombat Avatar answered Sep 20 '22 15:09

zombat


http://codex.wordpress.org/Function_Reference/register_activation_hook

The function register_activation_hook (introduced in WordPress 2.0) registers a plugin function to be run when the plugin is activated.

like image 22
Dominic Barnes Avatar answered Sep 20 '22 15:09

Dominic Barnes