maybe_add_column

Add column to database table, if column doesn't already exist in table.

Description

maybe_add_column( (string) $table_name, (string) $column_name, (string) $create_ddl ); 

Parameters (3)

0. $table_name (string)
Database table name
1. $column_name (string)
Table column name
2. $create_ddl (string)
SQL to add column to table.

Usage

  1. if ( !function_exists( 'maybe_add_column' ) ) { 
  2. require_once ABSPATH . '/wp-admin/install-helper.php'; 
  3.  
  4. // Database table name 
  5. $table_name = ''; 
  6.  
  7. // Table column name 
  8. $column_name = ''; 
  9.  
  10. // SQL to add column to table. 
  11. $create_ddl = ''; 
  12.  
  13. // NOTICE! Understand what this does before running. 
  14. $result = maybe_add_column($table_name, $column_name, $create_ddl); 
  15.  

Defined (2)

The function is defined in the following location(s).

/wp-admin/install-helper.php  
  1. function maybe_add_column($table_name, $column_name, $create_ddl) { 
  2. global $wpdb; 
  3. foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) { 
  4.  
  5. if ($column == $column_name) { 
  6. return true; 
  7.  
  8. // Didn't find it, so try to create it. 
  9. $wpdb->query($create_ddl); 
  10.  
  11. // We cannot directly tell that whether this succeeded! 
  12. foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) { 
  13. if ($column == $column_name) { 
  14. return true; 
  15. return false; 
/wp-admin/includes/upgrade.php  
  1. function maybe_add_column($table_name, $column_name, $create_ddl) { 
  2. global $wpdb; 
  3. foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) { 
  4. if ($column == $column_name) { 
  5. return true; 
  6.  
  7. // Didn't find it try to create it. 
  8. $wpdb->query($create_ddl); 
  9.  
  10. // We cannot directly tell that whether this succeeded! 
  11. foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) { 
  12. if ($column == $column_name) { 
  13. return true; 
  14. return false;