views:

41

answers:

3

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.

+1  A: 

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.

Dominic Barnes
Thanks Dominic. I appreciate the help.
Scott B
+1  A: 

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
     }
}
zombat
Thanks Zombat, and especially for the example. One question: Is it possible to have a working plugin (with code that executes as long as the plugin is activated) that also has an activation hook?
Scott B
Not quite sure I follow. Anything inside the function that you register as an activation hook will be run whenever the "activate plugin" action occurs in the wordpress admin panel. You can have a bunch of other code inside the plugin classes that will do other stuff, but not rely on activation hooks. It can just be used normally. Sorry if that doesn't answer your question, I didn't quite understand what you're asking...?
zombat
I figured it out. I was confused about where to put the init for the plugin and where to put the activation hook.
Scott B
A: 

remember also once your plugin is being deactivated by yourself/user you can remove any tables options that you have stored in the wp database, I wrote a little post about this recently talking about the wp register_deactivation_hook() function..

http://www.martin-gardner.co.uk/how-to-get-your-wordpress-plugin-to-drop-table-from-the-database/

    <?php
    register_deactivation_hook( __FILE__, ‘pluginUninstall’ );

    function pluginUninstall() {
      global $wpdb;
      $thetable = $wpdb->prefix."your_table_name";
      //Delete any options that's stored also?
      //delete_option('wp_yourplugin_version');
      $wpdb->query("DROP TABLE IF EXISTS $thetable");
    }
    ?>
Marty