如何修复WordPress自定义插件正常运行却显示「Database Update Required」提示的问题
解决WordPress插件持续弹出「Database Update Required」提示的问题
我看了你的插件代码和截图,问题出在数据库表创建逻辑的执行时机上——你把dbDelta($sql)放在了短码函数里,这意味着每次页面加载、调用这个短码的时候,都会触发数据库结构检查,WordPress就会误以为数据库需要更新,所以一直弹出提示。
问题根源
你的insert_into_db()函数是短码回调,每次页面渲染时都会执行,里面的dbDelta($sql)会告诉WordPress:「我可能修改了数据库结构」,系统就会触发更新提示,哪怕表已经存在了。
修复方案
我们需要把数据库表的初始化逻辑移到插件激活钩子里,只有当插件第一次激活(或者版本更新需要改表结构)的时候才执行,而不是每次短码运行都执行。同时添加版本跟踪,避免重复执行表创建操作。
修改后的完整代码如下:
<?php /** * Plugin Name: Content Creator 2 plugin * Plugin URI: http://www.nodomain.com * Description: This plugin will create a simple HTML-form with 3 input fields and store the information into a stage table. * Version: 1.0 * Author: Murat Kilic * Author URI: http://www.nodomain.com * License: GPLv3 **/ // 插件激活时执行数据库初始化 register_activation_hook(__FILE__, 'cc2plugin_install'); function cc2plugin_install() { global $wpdb; $table_name = $wpdb->prefix . "cc2testplugin"; $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE IF NOT EXISTS $table_name ( `id` MEDIUMINT NOT NULL AUTO_INCREMENT, `stagename` TEXT NOT NULL, `capacity` MEDIUMINT NOT NULL, `url` TEXT NOT NULL, UNIQUE (`id`) ) $charset_collate;"; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql); // 存储当前插件的数据库版本,后续更新表结构时可以用这个版本号判断 add_option('cc2plugin_db_version', '1.0'); } function insert_into_db() { ob_start(); ?> <!-- HTML表单 --> <form action="#v_form" method="post" id="v_form"> <label for="stagename"><h3>Name of stage:</h3></label> <input type="text" name="stagename" id="stagename"> <label for="capacity"><h3>Max capacity of stage:</h3></label> <input type="number" min="1000" max="50000" name="capacity" id="capacity"> <label for="url"><h3>Type MAP location (url):</h3></label> <input type="url" name="url" id="url"> <input type="submit" value="submit" name="submit_form"> </form> <?php $html = ob_get_clean(); // 处理表单提交 if (isset($_POST["submit_form"])) { global $wpdb; $table_name = $wpdb->prefix . "cc2testplugin"; $stagename = strip_tags($_POST["stagename"]); $capacity = strip_tags($_POST["capacity"]); $url = esc_url($_POST["url"]); // 用WordPress自带的函数更安全 $wpdb->insert( $table_name, array( 'stagename' => $stagename, 'capacity' => $capacity, 'url' => $url ) ); $html = "<p>The stage with following name <strong>$stagename</strong> was successfully inserted! Thanks.</p>"; } return $html; } add_shortcode('cc2testplugin','insert_into_db'); ?>
关键修改点说明
- 注册激活钩子:用
register_activation_hook把表创建逻辑绑定到插件激活事件,只有激活插件时才会执行一次。 - 添加数据库版本跟踪:用
add_option存储当前数据库版本,以后如果需要修改表结构,可以对比版本号来决定是否执行更新,避免重复触发dbDelta。 - 优化数据安全:把
$_POST["url"]换成esc_url(),这是WordPress推荐的安全处理方式,防止恶意URL输入。
后续操作
- 替换你的插件代码,然后先禁用再重新激活插件(确保激活钩子执行)。
- 刷新后台,「Database Update Required」的提示应该就消失了。
内容的提问来源于stack exchange,提问作者Murat Kilic
相关产品推荐
相关产品推荐

