I have read a bunch a posts about how to create a SQL table for Wordpress, when you "activate" a custom plugin. However, I am looking at the database and the table is not being created.
How do I create a table using a Wordpress plugin?
The code below is intended to create a table called "PICFCounter" and then populate that table with some initial data using function 'PICFCounter_install_data'.
global $PICF_db_version;
$PICF_db_version = '1.0';
register_activation_hook( __FILE__, 'PICFCounter_install' );
register_activation_hook( __FILE__, 'PICFCounter_install_data' );
function PICFCounter_install () {
global $wpdb;
global $PICF_db_version;
$table_name = $wpdb->prefix . "PICFCounter"; // Create a prefix for table PICFCounter
$charset_collate = $wpdb->get_charset_collate();
//Check to see if the table exists
if($wpdb->get_var( "show tables like '$table_name'") != $table_name)
{
$sql = "CREATE TABLE $table_name (
ID int(25) NOT NULL auto_increment,
City varchar(55) DEFAULT '' NOT NULL,
Event_Date date NOT NUll,
Counter_Value int(56) NOT NULL AUTO_DECREMENT,
PRIMARY KEY (ID)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
}
function PICFCounter_install_data() {
global $wpdb;
$table_name = $wpdb->prefix . "PICFCounter";
$city = 'Calgary';
$date = '2022-01-11'; //date('Y-m-d H:i:s');
$c = '25';
$wpdb->insert(
$table_name,
array(
'City' => $city,
'Event_Date' => $date,
'Counter_Value' => $c
)
);
}