WordPress代码解析之dbDelta($sql)

Author: 陌小雨Date: 2017-11-29View: 32

路漫漫其修远兮,吾将上下而求索。

以分析微信公众号插件为例来讲解dbDelta()的用法

add_action( 'plugins_loaded', 'create_history_table' );
function create_history_table(){
global $wpdb;
$table_name =DB_TABLE_WPWSL_HISTORY;
$sql = "CREATE TABLE $table_name (
id bigint(20) NOT NULL KEY AUTO_INCREMENT,
openid varchar(100) NOT NULL,
keyword varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
is_match char(1) NOT NULL,
time datetime NOT NULL
);";

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

plugins_loaded 所有插件加载完毕后执行此动作函数。

dbDelta()主要就是用来新建数据库表