首页 文章

尽管是全局的,$ wpdb仍为null

提问于
浏览
3

我正在创建一个插件,需要创建一个数据库并将数据插入其中,我已经完成了创建部分的表,但每当我尝试使用 $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');

这是表单提交文件:

<?php

function handle() {
    global $wpdb;

    if (isset($_POST['submit'])) {
        $wpdb->insert('wp_testing', array('name' => "test"));
    }
}

handle();

我读了这个问题:$wpdb is null even after 'global $wpdb并且很不清楚,但似乎表明 $wpdb 必须在一个函数中使用,所以我把它包装成一个 . 有关为什么会这样的想法?

1 回答

  • 4

    fix 如果您在不加载WordPress的情况下将表单直接发布到PHP文件,除非您需要 wp-load.php ,否则它的所有功能都不可用 . 这就是 add_action$wpdb 未定义的原因 .

    请参阅下面的评论和原始答案,了解在WordPress中发布表单的详细信息和其他方法 .

    original answer 你似乎没有将 handle() 函数绑定到任何钩子,因此它正在加载并运行,因为WordPress包含必要的文件,但在它实际加载之前 $wpdb . 那个's why $wpdb is not defined - it doesn't还存在 . 试试这个:

    <?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();
    

相关问题