Wordpress:表创建功能失败

时间:2019-03-28 12:00:18

标签: wordpress

我正在尝试使用wordpress钩子创建一个新的mysql表。我的代码:

// this code is inside the main plugin file with the commented header
// other code in this file works as expected.

  // create grid table
  function createGridTable() {
    global $wpdb;
    $charset_collate = $wpdb->get_charset_collate();

    $createGridTableQuery = 'CREATE TABLE IF NOT EXISTS ' . $wpdb->get_blog_prefix() . 'priceGrids (
      gridId mediumint(10) NOT NULL AUTO_INCREMENT,
      PRIMARY KEY  (gridId),
    ) $charset_collate;';
    // run the built query statement
    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
    dbDelta( $createGridTableQuery );
    // $wpdb->query($createGridTableQuery);
  }

  function runActivationFunctions () {
    createGridTable();
    // createLinkTable();
  }
  register_activation_hook(plugin_dir_url(__FILE__), 'runActivationFunctions');

在禁用并重新激活插件mysql后,将显示以下内容:

mysql> show tables;
+-----------------------+
| Tables_in_wptest2     |
+-----------------------+
| wp_commentmeta        |
| wp_comments           |
| wp_links              |
| wp_options            |
| wp_postmeta           |
| wp_posts              |
| wp_term_relationships |
| wp_term_taxonomy      |
| wp_termmeta           |
| wp_terms              |
| wp_testCreateViaCli   | // created via cli
| wp_usermeta           |
| wp_users              |
+-----------------------+
13 rows in set (0.00 sec)

遵循该语法指南似乎无法解决问题:https://codex.wordpress.org/Creating_Tables_with_Plugins

// example code
 global $wpdb;

 $charset_collate = $wpdb->get_charset_collate();

 $sql = "CREATE TABLE $table_name (   id mediumint(9) NOT NULL
 AUTO_INCREMENT,   time datetime DEFAULT '0000-00-00 00:00:00' NOT
 NULL,   name tinytext NOT NULL,   text text NOT NULL,   url
 varchar(55) DEFAULT '' NOT NULL,   PRIMARY KEY  (id) )
 $charset_collate;";

 require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta(
 $sql );

有人在我的代码中看到错误了吗?我认为我正在遵守规则,但是通过wordpress挂钩未生成任何表。

不确定是否相关,但是我在浏览器控制台上加载到wordpress网站的每个页面上都会得到此信息:

Unchecked runtime.lastError: The message port closed before a response was received.

1 个答案:

答案 0 :(得分:0)

请使用以下代码,以便我认为您可以添加表格。

function createGridTable() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'priceGrids ';
    $charset_collate = $wpdb->get_charset_collate();

    $createGridTableQuery = "CREATE TABLE IF NOT EXISTS $table_name  (
      gridId mediumint(10) NOT NULL AUTO_INCREMENT,
      PRIMARY KEY  (gridId),
    ) $charset_collate;";
    // run the built query statement
    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
    dbDelta( $createGridTableQuery );
    // $wpdb->query($createGridTableQuery);
  }

  function runActivationFunctions () {
    createGridTable();
    // createLinkTable();
  }
  register_activation_hook(__FILE__, 'runActivationFunctions');

经测试可正常工作