February Flash Sale

lovey-dovey week sale: Up to 70% off. Hurry before it ends!
Save Now

Days

Hrs

Min

Sec

Product successfully added to your shopping cart.

View Categories

WordPress – What is the $wpdb variable in WordPress, and how can you use it to improve the following code?

< 1 min read

Table of Contents

Using the $wpdb global object

WordPress provides a global object, $wpdb, which is an instantiation of the wpdb class. By default, $wpdb is instantiated to talk to the WordPress database.

The recommended way to access $wpdb in your WordPress PHP code is to declare $wpdb as a global variable using the global keyword, like this:

global $wpdb;
$results = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}options WHERE option_id = 1", OBJECT );

Alternatively, if the above doesn’t suit your needs for whatever reason, use the superglobal $GLOBALS in the following manner:

 $results = $GLOBALS['wpdb']->get_results( "SELECT * FROM {$wpdb->prefix}options WHERE option_id = 1", OBJECT );