我已经在数据库中手动创建了一个表,并且运行良好。
现在,每当我激活模板时,我希望在数据库中自动创建该表,因此我将以下代码放入
functions.php
文件中:
register_activation_hook( get_template_directory() . 'functions.php', 'Test_db_table' );
但是激活我的模板后没有创建任何表格。
编辑:
通过检查一个插件,我发现它使用了如下代码:
register_activation_hook( plugin_dir_path( __FILE__ ) . 'simple.php', 'create_db_table' );
现在我想为我的模板重写类似的内容,以便在激活我的模板时创建所需的表。
编辑2:
我也尝试过这个方法,但还是没有得到答案:
register_activation_hook( __FILE__, 'Test_db_table' );
离开您在问题中创建的最后一个示例,您可以为激活挂钩提供自定义函数。让我们调用函数“create_custom_table”。
在我们的函数中,我们需要包含WP管理文件upgrade.php,因为它具有执行所需SQL所需的函数。
我们还可以使用 $wpdb WordPress 全局来轻松获取所使用的表前缀,这样插件就可以更加动态,并且前缀不会被硬编码。您还可以从 $wpdb 获取字符集/排序规则信息,您需要将其添加到 SQL 中。
我在代码中添加了注释,以便您可以继续操作。这只是一个示例,请根据需要进行更改。
register_activation_hook( __FILE__, 'create_custom_table' );
function create_custom_table() {
global $wpdb;
// Get the prefix of the WordPress database
$table_prefix = $wpdb->prefix;
// Set the name of the table
$table_name = $table_prefix . 'your_table_name';
// Query for checking if table exists
$table_exists = $wpdb->get_var("show tables like '$table_name'");
// If the table does not exist, create it
if (!$table_exists) {
// Set create SQL
$sql = "CREATE TABLE `{$table_name}` (
`field1` int(11) NOT NULL,
`field2` varchar(200) DEFAULT NULL,
KEY `your_index` (`field1`,`field2`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1";
// Include upgrade.php so we get access to dbDelta function
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
// Eecute the SQL
dbDelta($sql);
}
}