Matt
  • 1

How to create a custom database table when activate a plugin?

  • 1

I want to create a custom database table when activate my plugin. Could you please give me a sample code for create a simple database table.

1 Answer

  1. To create a custom database table in WordPress when activating a plugin, add the following code in plugin file.

    register_activation_hook(__FILE__, 'create_custom_table');
    
    function create_custom_table()
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'custom_table';
        $charset_collate = $wpdb->get_charset_collate();
        $sql = "CREATE TABLE $table_name (
            id int(11) NOT NULL AUTO_INCREMENT,
            column1 varchar(255) NOT NULL,
            column2 text NOT NULL,
            PRIMARY KEY  (id)
        ) $charset_collate;";
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }
    
    
    Note:
    • register_activation_hook function will be triggered when plugin is activated
    • The dbDelta function is used to create the table.
    • Make sure to replace custom_table with your desired table name, and column1 and column2 with your desired column names.

     

Leave an answer

You must login to add an answer.