Wordpress variable wpdb undefined

I am writing a plugin and trying to query some data from a user table in my database using:

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

but just get an Undefined error: wpdb

Any idea why this is not working? I followed documents and searched Google, no luck. Still quite new to WP plugins, perhaps something obvious.

Thanks!

+7
source share
2 answers

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

+26
source

One note to add: you cannot use global inside a class, and of course you must use global to make your objects work with $wpdb .

While you cannot use global directly inside the class, you must declare $wpdb as global inside the function inside the class, and that works.

eg. This gives you an error message:

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

Because global cannot be used directly inside a class. Similarly, just referring to $wpdb inside the class, you also get an error message because the object does not know what $wpdb . You must declare $wpdb as global inside a function inside your class.

eg. This works great:

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

... and because $wpdb declared global inside a function inside a class that you can use.

+2
source

All Articles