If you want to create your own database tables while installing your custom WordPress plugin on WordPress websites. In this tutorial, I will explain how to creating database tables with plugins in WordPress.
This tutorial will help you while you are developing your custom plugins. To create database tables with your plugins, you need to add the below code to your plugin file:
1 2 | require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql ); |
Use the below code to get the database table prefix and use that before your custom table names.
1 | $table_name = $wpdb->prefix . "freewebmentorlive"; |
After that write your custom SQL queries to like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | global $wpdb; $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE $table_name ( id mediumint(9) NOT NULL AUTO_INCREMENT, time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL, name tinytext NOT NULL, text text NOT NULL, url varchar(55) DEFAULT '' NOT NULL, PRIMARY KEY (id) ) $charset_collate;"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql ); |
Below is the complete code to create database tables in your WordPress custom plugins.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | <?php global $jal_db_version; function jal_install() { global $wpdb; global $jal_db_version; $table_name = $wpdb->prefix . 'liveshoutbox'; $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE $table_name ( id mediumint(9) NOT NULL AUTO_INCREMENT, time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL, name tinytext NOT NULL, text text NOT NULL, url varchar(55) DEFAULT '' NOT NULL, PRIMARY KEY (id) ) $charset_collate;"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql ); } register_activation_hook( __FILE__, 'jal_install' ); ?> |
Do you like & share this article with your friends, and don’t forget to follow us on Facebook and Twitter to learn cool WordPress tutorials.
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: create databse table with wp plugins, wordpress mysql tutorial, wordpress tutorial, wordpress tutorial for beginner, wordpress tutorial for beginners, wordpress tutorials, wordpress tutorials for beginners