开发者

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 followe开发者_JS百科d the docs and scoured Google, with no luck. Still pretty new to WP plugins so probably something obvious.

Thanks!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜