How to create Custom Database Table on Plugin Activation
- February 19, 2016
- Leave a comment
You might require a custom database table to store your records originating from your custom plugin. You can utilize WordPress’ hook named “register_activation_hook” to perform any task when a plugin is activated. From this article, you will learn how to make a custom database table with some essential fields once plugin is activated.
You can utilize the following code to create another table in your database on plugin activation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
function pt_my_activation_function() { global $wpdb; $table_name = $wpdb->prefix . 'ptcontactform'; $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE $table_name ( id mediumint(9) NOT NULL AUTO_INCREMENT, Name varchar(255), Email varchar(255), Cellnumber varchar(255), City varchar(255), UNIQUE KEY id (id) ) $charset_collate;"; $result = $wpdb->query($sql); } register_activation_hook(__FILE__,'pt_my_activation_function'); |
The hook will be called on activation that will further proceed to a function provided in the parameters i.e. “pt_my_activation_function”. This function defines a global variable and runs a query to create a new table in the database. $wpdb->prefix will automatically get the prefix of your database already in use. You can change the query as per your requirements.
User Comments