Adding code to a plugin that only runs on first launch?

Is it possible to wrap the code in a special function that is executed only at the first start of the plugin?

I have a database code that I need to run when the plugin is activated, but after that the code should not run again.

+6
php plugins wordpress
source share
3 answers

Yes it is possible. You can register the plug-in activation hook, which is launched only after the plug-in is activated. I dug up an old plugin that I wrote for some sample 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 } } 
+9
source share

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

The register_activation_hook function (introduced in WordPress 2.0) registers the plug-in function of the plug-in when the plug-in is activated.

+2
source share

remember also, as soon as your plugin is deactivated by the user / yourself, you can delete any parameters of the tables that you saved in the wp database, I wrote a short note about this recent talk about the wp function register_deactivation_hook ().

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 stored also? //delete_option('wp_yourplugin_version'); $wpdb->query("DROP TABLE IF EXISTS $thetable"); } ?> 
+1
source share

All Articles