Jac*_*ris 3 php mysql database wordpress
我正在开发一个插件,需要创建一个数据库并将数据插入其中,我已经完成了表创建部分,但每当我尝试使用$wpdb插入数据时都会出现错误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');
Run Code Online (Sandbox Code Playgroud)
这是表单提交文件:
<?php
function handle() {
global $wpdb;
if (isset($_POST['submit'])) {
$wpdb->insert('wp_testing', array('name' => "test"));
}
}
handle();
Run Code Online (Sandbox Code Playgroud)
我读到了这个问题:$ wpdb即使在'global $ wpdb之后也是空的并且很不清楚,但似乎表明$wpdb必须在函数中使用,所以我把它包装在一个中.有关为什么会这样的想法?
修复
如果您在不加载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' );
Run Code Online (Sandbox Code Playgroud)
我还考虑为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' );
Run Code Online (Sandbox Code Playgroud)
要么
<?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();
Run Code Online (Sandbox Code Playgroud)