我编写了一个简单的Wordpress插件来创建一个新的数据库表。应该在插件激活时创建新表。当我尝试激活插件时,出现以下错误:
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.
这显然是因为没有定义$wbdb。xDebug输出以下内容:
[Mon Feb 04 ] [error] PHP Notice: Undefined variable: wpdb in test.php on line 13
整个插件包括以下内容:
<?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\');
?>
我没有安装其他插件。为什么没有定义$wpdb?激活插件时,是否有创建新数据库表的标准方法?
SO网友:akTed
您的插件试图在$wpdb存在之前访问它。你需要用action hook, 像这样:
<?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
*/
add_action( \'init\', \'test_install_plugin\' );
function test_install_plugin() {
global $wpdb;
global $test_db_name;
$test_db_name = $wpdb->prefix . \'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);
}
// commented out for now, worry about running activation later
// register_activation_hook(__FILE__,\'test_install_plugin\');
我强烈建议你把你能在谷歌上找到的与WordPress中的动作和过滤器相关的一切都吃掉。它们是您需要充分理解的核心概念,以便有效地创建插件和主题。