When a WordPress plugin needs to store custom data, it often creates its own database tables. How does the plugin usually create these tables?
Think about how plugins safely create tables only once during activation.
WordPress plugins use register_activation_hook to run code when the plugin activates. Inside that code, they use dbDelta() to create or update tables safely. This avoids errors and ensures tables are created only once.
Which SQL statement correctly creates a plugin table with the proper charset and collation in WordPress?
WordPress recommends using InnoDB engine and utf8mb4 charset for compatibility.
Option B uses InnoDB engine and utf8mb4 charset with unicode collation, which is the recommended setup for WordPress plugin tables to support emojis and multilingual content.
Consider this plugin activation code snippet:
global $wpdb; $table_name = $wpdb->prefix . 'myplugin'; $sql = "CREATE TABLE $table_name ( id mediumint(9) NOT NULL AUTO_INCREMENT, name varchar(255) NOT NULL, PRIMARY KEY (id) )"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql );
Why might the table not be created?
Check the SQL syntax carefully, especially punctuation inside the string.
The SQL string ends with a closing parenthesis followed immediately by a semicolon inside the string. dbDelta expects no semicolon at the end of the SQL statement. This causes the table creation to fail.
A plugin stores its database version in the option myplugin_db_version. On activation, it runs this code:
global $wpdb;
$table_version = get_option('myplugin_db_version');
if ( $table_version != '1.0' ) {
// create or update tables
update_option('myplugin_db_version', '1.0');
}If the option myplugin_db_version does not exist before activation, what will be its value after activation?
Think about what update_option does after the check.
If the option does not exist, get_option returns false, so the condition is true. The plugin then updates the option to '1.0'. After activation, the option value is '1.0'.
When a plugin updates to a new version that changes the database schema, what is the best practice to update the plugin's database tables safely?
Think about how to avoid data loss and keep schema in sync.
Storing a database version in options and checking it on admin_init allows the plugin to run dbDelta() safely to update tables incrementally without losing data. Dropping tables or requiring reinstall causes data loss or poor user experience.