Wordpress wpdb undefined variable

I'm writing a plugin and trying to request some data from a custom table in my database using:

$current_text = $wpdb->get_results("SELECT text FROM addtext ORDER BY id DESC LIMIT 1");

but just get the error Undefined variable: wpdb

Any idea why this isn't working? I've followed the docs and scoured Google, with no luck. Still pretty new to WP plugins so probably something obvious.

Thanks!

Answers


I needed to use global $wpdb; in my function.


One note to add: You cannot use global inside a class, and of course you have to use global in order to get your objects to work using $wpdb.

While you can't use global immediately inside a class, you must declare $wpdb as global inside a function inside the class, and this does work.

e.g. This gives you an error:

class wpdb_test {
        global $wpdb; // can't use global as a direct 'child' of a class
        public function __construct () {
            ...
        }
}

Because global can't be used directly inside a class. Likewise, simply referencing $wpdb inside the class also gives you an error because the object doesn't know what $wpdb is. You have to declare $wpdb as global from inside a function that is inside your class.

e.g. This works just fine:

class wpdb_test {
        public $variable_name;
        public function __construct () {
            global $wpdb; // safe to use because it's inside a function
            ...
        }
}

...and because $wpdb has been declared global inside a function inside a class you are able to use it.


Need Your Help

Flask url_for generating http URL instead of https

python url-routing flask werkzeug

I am using url_for to generate a redirect URL when a user has logged out:

Why am I getting a "SystemStackError: stack level too deep" in my rails3 beta4 model

ruby-on-rails ruby activerecord ruby-on-rails-3

I'm getting the following error: SystemStackError: stack level too deep when executing the following code in rails3 beta4 under ruby 1.9.2-rc1: