WP Custom plugin: Create table and insert data once.

This is my complete WordPress plugin file:

<?php
function wp_create_table_install()
{
    global $wpdb;

    $table_name = $wpdb->prefix.'createtable';
    $sql = 'CREATE TABLE '.$table_name.'(
        id INT(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
        name VARCHAR(75)
    );';

    require_once(ABSPATH.'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}

function wp_create_table_insert_data()
{
    global $wpdb;

    $table_name = $wpdb->prefix.'createtable';
    $id = 1;
    $name = 'WP Create Table!';

    $wpdb->insert($table_name, array('id' => $id, 'name' => $name));
}

register_activation_hook(__FILE__, 'wp_create_table_install');
register_activation_hook(__FILE__, 'wp_create_table_insert_data');
?>

When I activate the plugin, it always tries to create a table and insert data. How could I do it once, just in the first plugin activation?

Read More

Thank you.

Related posts

Leave a Reply

3 comments

  1. Unfortunately, there’s no way to run something on “install” – surprisingly, WordPress doesn’t provide any hooks for install as opposed to activation!

    The way people cope with this is to set and test an option – if the option is not set, then create the tables, and if it is set do nothing or do a DB upgrade. Options are read in and cached so there is no performance penalty to doing this.

    $opt = get_option(MYPLUGIN_OPTIONS);
    
    $opt['dbversion'] = 100;
    ...
    update_option(MYPLUGIN_OPTIONS, $opt);