Creating a custom table with PHP in WordPress

Hello Wp Rockers,
If you work with WordPress database then you must familiar
with some WordPress tables like wp_users, wp_posts, wp_comments etc.

Now if you want to create some more tables with custom columns.
Then here is a cool solution for you.

I’m going to create a new table wp_account. So I’m using
CREATE TABLE sql and set my column names with data types.
Take a look on the codes.


<?php
// CREATE TABLE WP_ACCOUNT
global $wpdb;
$table_name = $wpdb->base_prefix."account";

if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name){
$sql = "CREATE TABLE ".$wpdb->base_prefix."account(
account_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,

client_id VARCHAR(200) NOT NULL,

total_payment VARCHAR(200) NOT NULL,

payment_date VARCHAR(200) NOT NULL,

work_title VARCHAR(200) NOT NULL,

details LONGTEXT NULL
)";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta($sql);
}
?>

First I’m using $wpdb->base_prefix for use the current prefix (Example: wp_ ).
I checked the table already exist or not by using $wpdb->get_var. Finally dbDelta for manupulate the sql.

Use this code. Refresh your database and check the new table wp_account with all the custom fields.

Another thing, if you want to know about How to remove a table in WordPress, please check the tutorial.

Leave a Reply

Your email address will not be published. Required fields are marked *