I’ve written a simple WordPress plugin to create a new database table.
The new table ought to be created when the plugin is activated.
When I try to activate the plugin, I get the following error:
The plugin generated 3989 characters of unexpected output during activation. If you notice âheaders already sentâ messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.
emphasized text
This is obviously a result of the fact the $wbdb is not defined. xDebug outputs the following:
[Mon Feb 04 ] [error] PHP Notice: Undefined variable: wpdb in test.php on line 13
The entire plugin consists of the following:
<?php
/**
* Plugin Name: Test Plugin
* Plugin URI: http://everybytcaptive.com
* Description: A test plugin.
* Version: 1.0
* Author: Christopher Green
* Author URI: http://everybytecaptive.com
*/
$test_db_name = $wpdb->prefix . 'test_db_name';
function test_install_plugin() {
global $wpdb;
global $test_db_name;
$sql = "CREATE TABLE " . $test_db_name . " (
`id` int(9) NOT NULL AUTO_INCREMENT,
UNIQUE KEY id (id)
);";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
register_activation_hook(__FILE__,'test_install_plugin');
?>
I have no other plugins installed.
Why isn’t $wpdb defined?
Is there a standard way to create a new database table when activating a plugin?
$wpdb
is outside the scope of your plugin file, you needglobal $wpdb;
before using$wpdb->prefix
Your plugin is trying to access $wpdb before it exists. You need to wrap it in an action hook, like so:
I highly recommend devouring everything you can find with Google relating to actions and filters in WordPress. They are core concepts that you need to fully understand in order to create plugins and themes effectively.
Well, in my case the issue was due to a duplicate
db_table
creation process, and when I added anif statement
to check whether thedb_table
exists or not the issue was resolved.Here is how:
Now the plugin checks if the required table(s) exists or not before activation, if not exist then it will create it, if exists will escape the creation.