dongxu1875
2015-03-20 13:45 阅读 25
已采纳

如何清理使用wordpress的开关主题创建的自定义表?

I am creating a custom table in wordpress, while switching the theme from A to B, in the admin panel.

add_action('after_switch_theme', 'manage_student_reports');

function manage_student_reports() {
    $sql = "CREATE TABLE IF NOT EXISTS `wp_student_reports` (
     `report_id` int(20) NOT NULL AUTO_INCREMENT,
     `student_name` varchar(50) NOT NULL,
     `department` varchar(50) DEFAULT NULL,
     `percentage` tinyint(4) DEFAULT '0',
     PRIMARY KEY (`report_id`)
    );";

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

But when i switch back the theme from B to A (or something else), the table still exists in the wordpress database. Is there a way to drop it ?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    douhuike3199 douhuike3199 2015-03-20 14:36
    1. dbDelta() function does not remove the fields or tables, only adds and updates.
    2. after_switch_theme hook runs once when current theme is activated. To do things when your theme is deactivated, use switch_theme hook.
    3. In switch_theme hook call a function which will trigger a check if table exists (to be safe and avoid possible errors) and then run a custom DROP TABLE sql.
    点赞 评论 复制链接分享

相关推荐