Using WordPress ‘maybe_add_column()’ PHP function

The maybe_add_column() WordPress PHP function adds a column to a database table if it doesn’t already exist.

Usage

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

Example:

maybe_add_column( 'wp_custom_table', 'custom_column', 'ALTER TABLE wp_custom_table ADD custom_column VARCHAR(255) NOT NULL' );

Parameters

  • $table_name string: The name of the database table.
  • $column_name string: The name of the table column to add.
  • $create_ddl string: The SQL statement used to add the column.

More information

See WordPress Developer Resources: maybe_add_column

Examples

Add a Text Column

Add a new text column named “description” to the “wp_custom_table” table:

maybe_add_column( 'wp_custom_table', 'description', 'ALTER TABLE wp_custom_table ADD description TEXT NOT NULL' );

Add an Integer Column

Add a new integer column named “user_id” to the “wp_custom_table” table:

maybe_add_column( 'wp_custom_table', 'user_id', 'ALTER TABLE wp_custom_table ADD user_id INT NOT NULL' );

Add a Date Column

Add a new date column named “publish_date” to the “wp_custom_table” table:

maybe_add_column( 'wp_custom_table', 'publish_date', 'ALTER TABLE wp_custom_table ADD publish_date DATE NOT NULL' );

Add a Decimal Column

Add a new decimal column named “price” to the “wp_custom_table” table:

maybe_add_column( 'wp_custom_table', 'price', 'ALTER TABLE wp_custom_table ADD price DECIMAL(10,2) NOT NULL' );

Add a Unique Column

Add a new unique column named “email” to the “wp_custom_table” table:

maybe_add_column( 'wp_custom_table', 'email', 'ALTER TABLE wp_custom_table ADD email VARCHAR(255) NOT NULL UNIQUE' );