2

In my addon, I would like to check on activation, if a column of a specific table in the DB already exists to avoid to implement it for each activation.

Something like this :

class MainClassAddon{

     public function __construct(){
         register_activation_hook( __FILE__, array( $this, 'install' ) );
     }

     public function install(){

         if( /*Checking if column c in table wp_t exists*/ ){
             $wpdb->query("ALTER TABLE wp_t ADD c INT(1) NOT NULL DEFAULT 1");
         }
     }
}
new MainClassAddon();
register_uninstall_hook( __FILE__,  array( 'PluginNamespace\MainClassAddon', 'uninstall' ) );

2 Answers 2

2

I found this solution : here

So...

class MainClassAddon{

     public function __construct(){
         register_activation_hook( __FILE__, array( $this, 'install' ) );
     }

     public function install(){

         $row = $wpdb->get_results(  "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'wp_t' AND column_name = 'c'"  );

         if(empty($row)){
             $wpdb->query("ALTER TABLE wp_t ADD c INT(1) NOT NULL DEFAULT 1");
         }
     }
}
new MainClassAddon();
register_uninstall_hook( __FILE__,  array( 'PluginNamespace\MainClassAddon', 'uninstall' ) );
0

WordPress has a built-in function for this: maybe_add_column() https://developer.wordpress.org/reference/functions/maybe_add_column/

global $wpdb;
$table_name = $wpdb->prefix . 'wp_t';
$column_name = 'c';
$create_ddl = "ALTER TABLE $table_name ADD $column_name INT(1) NOT NULL DEFAULT 1;";

require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
maybe_add_column($table_name, $column_name, $create_ddl);

Applying it to your solution:

class MainClassAddon{

     public function __construct(){
         register_activation_hook( __FILE__, array( $this, 'install' ) );
     }

     public function install(){
         global $wpdb;
         $table_name = $wpdb->prefix . 'wp_t';
         $column_name = 'c';
         $create_ddl = "ALTER TABLE $table_name ADD $column_name INT(1) NOT NULL DEFAULT 1;";
    
         require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
         maybe_add_column($table_name, $column_name, $create_ddl);
     }
}
new MainClassAddon();
register_uninstall_hook( __FILE__,  array( 'PluginNamespace\MainClassAddon', 'uninstall' ) );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.