首页 > 解决方案 > 创建表格自定义插件时Wordpress插入数据

问题描述

嗨,我正在 wordpress 中创建一个表格

        $sql = "CREATE TABLE IF NOT EXISTS $wpdb->prefix" . "profil_member(
            id_profil bigint(20)UNSIGNED NOT NULL AUTO_INCREMENT,
            id_member bigint(20) UNSIGNED NOT NULL,
            id_subscription bigint(20) UNSIGNED NOT NULL,
            createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
            updatedAt DATETIME,
            state int DEFAULT 1,
            PRIMARY KEY(id_member,id_subscription),
            FOREIGN KEY (id_profil) REFERENCES $wpdb->prefix" . "profil(id),
            FOREIGN KEY (id_member) REFERENCES $wpdb->prefix" . "member(id)
            ) " . $wpdb->get_charset_collate();

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

我想在使用另一个表中的日期创建时填充此表

       if (version_compare($version, '1.7') < 0) {
            $this->populate_profil_member();
            update_option('my_plugin_version', '1.7');
        }

当前插件版本是 1.6。

如果我使用 1.7 更新加载插件,它会创建表但不插入数据并将插件更新到 1.7

如果我用创建表加载插件而不是插入它会创建表然后如果我用更新重新加载它会插入数据并更新到 1.7

有没有一种解决方案来创建表并同时插入数据。?

标签: phpmysqlwordpressplugins

解决方案


按照这个例子:

function insert_data_into_database() {
    global $wpdb;
    
    $welcome_name = 'Mr. WordPress';
    $welcome_text = 'Congratulations, you just completed the installation!';
    
    $table_name = $wpdb->prefix . 'your-table-name';
    
    $wpdb->insert( 
        $table_name, 
        array( 
            'time' => current_time( 'mysql' ), 
            'name' => $welcome_name, 
            'text' => $welcome_text, 
        ) 
    );
}

推荐阅读