· 8 years ago · Aug 01, 2018, 08:24 PM
1/**
2 * Core plugin class
3 */
4 require_once plugin_dir_path(__FILE__) . 'includes/class_my_plugin.php';
5
6
7 function run_my_plugin() {
8 $plugin = new my_plugin();
9 $plugin->run();
10 }
11
12 run_my_plugin();
13
14class my_plugin {
15
16private
17 $wpdb,
18 $table_prefix,
19 $charset_collate;
20
21
22public function __construct() {
23 global $wpdb;
24
25 $this->wpdb = &$wpdb;
26 $this->table_prefix = $this->wpdb->prefix . 'test_private_';
27 $charset_collate = $this->wpdb->get_charset_collate();
28
29}
30
31public function run() {
32
33 $table_name = $this->table_prefix . 'desks';
34
35
36 $sql = "CREATE TABLE IF NOT EXISTS $table_name (
37 some_id int(11) NOT NULL AUTO_INCREMENT,
38 some_title VARCHAR(50) NOT NULL,
39 PRIMARY KEY (desk_id)
40 ) $this->charset_collate;";
41
42 dbDelta($sql);
43
44}
45
46}
47
48if (is_admin()){
49 //manage the the database tables when registering or deactivating
50 register_activation_hook($loc, array($this, 'your_plugin_installation'));
51 register_deactivation_hook($loc, array($this, 'your_plugin_unset'));
52 register_uninstall_hook ($loc, 'your_plugin_uninstall');
53}
54
55// -------------------- Define actions to be taken when installing and uninstalling the Plugin --------------------
56function your_plugin_installation() {
57 create_data_tables();
58}
59
60function your_plugin_unset() {
61 //do whatever here
62}
63
64function your_plugin_uninstall() {
65 delete_db_tables();
66}
67
68function create_data_tables() {
69 global $wpdb;
70 require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
71 $table_name = $this->table_prefix . 'desks';
72 $charset_collate = $wpdb->get_charset_collate();
73 if( $wpdb->get_var("SHOW TABLES LIKE '".$table_name."'") != $table_name ) {
74 $sql = "CREATE TABLE IF NOT EXISTS ".$table_name;
75 $sql .= " (some_id int(11) UNSIGNED NOT NULL AUTO_INCREMENT, ";
76 $sql .= "some_title varchar(31) NOT NULL DEFAULT '', ";
77 $sql .= "PRIMARY KEY (some_id)) ".$charset_collate;
78 dbDelta( $sql );
79 }
80 // repeat the if {} statement for each table you want to create
81}
82
83function delete_db_tables() {
84 global $wpdb;
85 //delete your tables here
86}