我正在创建一个插件,需要创建一个数据库并在其中插入数据,我已经完成了表创建部分,但是每当我尝试使用$wpdb
插入数据时都会出现错误{ {1}}。
这是一个最小版本:
insert() could not be called on a null object
这是表单提交文件:
<?php
/*
Plugin Name: Test
*/
function activation() {
global $wpdb;
$table_name = $wpdb->prefix . 'testing';
$charset_collate = $wpdb->get_charset_collate();
# create table
if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
$sql = "CREATE TABLE " . $table_name . " (
id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
name TEXT NOT NULL,
PRIMARY KEY (id)
) " . $charset_collate . ";";
require_once(ABSPATH . "wp-admin/includes/upgrade.php");
dbDelta($sql);
}
}
function html($atts) {
$out = "";
return "<form action='wp-content/plugins/test/submit.php' method='post'><input type='text' name='name'><input type='submit' name='submit'></form>";
}
# setup and cleanup hooks
register_activation_hook(__FILE__, "activation");
add_shortcode('testing', 'html');
我读到了这个问题:$wpdb is null even after 'global $wpdb并且很不清楚,但似乎表明必须在函数中使用<?php
function handle() {
global $wpdb;
if (isset($_POST['submit'])) {
$wpdb->insert('wp_testing', array('name' => "test"));
}
}
handle();
,所以我把它包装成一个。关于这是为什么的任何想法?
答案 0 :(得分:5)
<强>修复
如果您在不加载WordPress的情况下将表单直接发布到PHP文件,除非您需要wp-load.php
,否则它的所有功能都不可用。这就是add_action
和$wpdb
未定义的原因。
有关详细信息以及在WordPress中发布表单的其他方式,请参阅下面的评论和原始答案。
原始回答
您似乎没有将handle()
函数绑定到任何挂钩,因此它正在加载并运行,因为WordPress包含必要的文件,但在它实际加载$wpdb
之前。这就是为什么没有定义$ wpdb - 它还不存在。试试这个:
<?php
function handle() {
global $wpdb;
if( isset( $_POST[ 'submit' ] ) ){
$wpdb->insert( 'wp_testing', array( 'name' => 'test' ) );
}
}
//handle();
add_action( 'init', 'handle' );
我还考虑为handle()
函数添加前缀(或者更好,将其包装在类中)以避免命名冲突。类似的东西:
<?php
function jacob_morris_handle() {
global $wpdb;
if( isset( $_POST[ 'submit' ] ) ){
$wpdb->insert( 'wp_testing', array( 'name' => 'test' ) );
}
}
//handle();
add_action( 'init', 'jacob_morris_handle' );
或
<?php
class JacobMorris {
function handle() {
global $wpdb;
if( isset( $_POST[ 'submit' ] ) ){
$wpdb->insert( 'wp_testing', array( 'name' => 'test' ) );
}
}
function __construct(){
add_action( 'init', array( $this, 'handle' ) );
}
}
new JacobMorris();