WordPress Version: 4.9
/**
* Add column to database table, if column doesn't already exist in table.
*
* @since 1.0.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $table_name Database table name
* @param string $column_name Table column name
* @param string $create_ddl SQL to add column to table.
* @return bool False on failure. True, if already exists or was successful.
*/
function maybe_add_column($table_name, $column_name, $create_ddl)
{
global $wpdb;
foreach ($wpdb->get_col("DESC {$table_name}", 0) as $column) {
if ($column == $column_name) {
return true;
}
}
// Didn't find it, so try to create it.
$wpdb->query($create_ddl);
// We cannot directly tell that whether this succeeded!
foreach ($wpdb->get_col("DESC {$table_name}", 0) as $column) {
if ($column == $column_name) {
return true;
}
}
return false;
}