How create table (if not exists) by activation plugin?
Note: plugin works fine if table exists, but i need create table if not exists
what i try:
function alicelf_bookmark() {
global $wpdb;
$table_name = $wpdb->prefix . "alice_user_bookmarks";
$charset_collate = '';
if ( ! empty( $wpdb->charset ) )
$charset_collate = "DEFAULT CHARACTER SET {$wpdb->charset}";
if ( ! empty( $wpdb->collate ) )
$charset_collate .= " COLLATE {$wpdb->collate}";
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id INT NOT NULL AUTO_INCREMENT,
user_id INT,
name VARCHAR(255),
shipping_address VARCHAR(255),
user_notes TEXT,
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
//some other plugin stuff..
}
add_action('wp_footer', 'alicelf_bookmark');
Maybe im use wrong action?
When your plugin requires it’s own table, you will want to take into account that this table can change over time. You know it will change (from nothing to your first version) on first install. Later it can change when a user updates the plugin.
A great way to do this is to store a database version number in the options table, and check if it’s updated. If the version number in the options table doesn’t match the one in your plugin, an install is needed.
This brings us to how your plugin should handle changes in the table structure. A simple approach could include a whole lot of if-tests and custom ALTER TABLE queries (the same queries aren’t necesserily needed when upgrading from 1.0 to 3.0 as the ones you would need to upgrade from 1.0 to 3.0). This could become hard to work with pretty fast.
It is generally better to leave the ALTER TABLE statements to WordPress’ own dbDelta function, which will generate the statements you need.
For further reading, a great guide to Creating Tables with Plugins can be found in the Codex.
Found solution: Just need register activate and change wp_head instead wp_footer