将表添加到WordPress数据库

时间:2020-05-23 作者:Victoria Whitehead

我正在使用下面的脚本向wordpress数据库添加一个表,但什么都没有发生。我不确定我做错了什么。

任何建议都将不胜感激。

     function vw_postcode_checker_create_db ()
    {
        global $wpdb;
      global $tableprefix;

        // Create Table Name
        $table_name =$tableprefix . "vw_postcode_checker";

        // Write Query to add table to database
        if ($wpdb->get_var(\'SHOW TABLES LIKE\'.$table_name) !=$table_name)
        {
                $sql = "CREATE TABLE " . $table_name . " (
                    id INTEGER(10) UNSIGNED AUTO_INCREMENT,
                    postcode  varchar(250)   NOT NULL,
                    area varchar(250)   NOT NULL
                    PRIMARY KEY (id)
                )";
    // Execute Query to Create Table
    require_once (ABSPATH . \'wp-admin/includes/upgrade.php\');
                dbDelta($sql);
                add_option (\'vw_postcode_checker_version\', \'0.1\');
        }
        }
// Register table function
register_activation_hook (__FILE__,\'vw_postcode_checker_create_db\');

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

尝试:

function vw_postcode_checker_create_db () {
    global $wpdb;

    // Create Table Name
    $table_name = $wpdb->prefix . "vw_postcode_checker";

    // Write Query to add table to database
    if ( $wpdb->get_var("SHOW TABLES LIKE \'$table_name\'") != $table_name) {
        $sql = "CREATE TABLE $table_name (
            id INTEGER(10) UNSIGNED AUTO_INCREMENT,
            postcode  varchar(250) DEFAULT \'\'  NOT NULL,
            area varchar(250) DEFAULT \'\'  NOT NULL,
            PRIMARY KEY (id)
         );";
        // Execute Query to Create Table
        require_once (ABSPATH . \'wp-admin/includes/upgrade.php\');
        dbDelta($sql);
        add_option (\'vw_postcode_checker_version\', \'0.1\');
    }
}
// Register table function
register_activation_hook (__FILE__,\'vw_postcode_checker_create_db\');
注意使用$wpdb->prefix 以及之后的关闭PRIMARY KEY (id)

https://codex.wordpress.org/Creating_Tables_with_Plugins