插件生成了%x个字符的意外输出,未定义$wpdb

时间:2013-02-04 作者:cg433n

我编写了一个简单的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?激活插件时,是否有创建新数据库表的标准方法?

3 个回复
最合适的回答,由SO网友:Milo 整理而成

$wpdb 超出插件文件的范围,您需要global $wpdb; 使用前$wpdb->prefix

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中的动作和过滤器相关的一切都吃掉。它们是您需要充分理解的核心概念,以便有效地创建插件和主题。

SO网友:Jodyshop

嗯,在我的情况下,问题是由于重复db_table 创建过程中if statementcheck 是否db_table 是否存在问题已解决。

Here is how:

define( \'TABLEName\', $wpdb->prefix . \'test_table\' );

if( $wpdb->get_var( "show tables like \'" . TABLEName . "\'" ) != TABLEName ) {
create table;
}
现在插件检查required table(s) exists 或者不在激活之前,如果不存在,则它将创建它,如果存在,则将逃避创建。

结束

相关推荐

wp_list_tables bulk actions

如何在扩展的WP\\U List\\U表中触发批量操作。我一直在将以下批量操作添加到may table的选择框中,但在Apply上不会发生任何事情下面是我如何添加批量操作的function get_bulk_actions() { $actions = array( \'delete\' => \'Delete\', \'parsing\' => \'Parsen\' );