Class Reference/wpdb

Talking to the Database: The wpdb Class

WordPress defines a class called wpdb, which contains a set of functions used to interact with a database. Its primary purpose is to provide an interface with the WordPress database, but can be used to communicate with any other appropriate database. The class source code is loosely based on the ezSQL class; written and maintained by Justin Vincent

Using the $wpdb Object

Warning: Methods in the wpdb() class should not be called directly. Use the global $wpdb object instead!

WordPress provides a global object variable, $wpdb, which is an instantiation of the wpdb class defined in /wp-includes/wp-db.php. By default, $wpdb is instantiated to talk to the WordPress database. To access $wpdb in your WordPress PHP code, declare $wpdb as a global variable using the global keyword, or use the superglobal $GLOBALS in the following manner:


// 1st Method - Declaring $wpdb as global and using it to execute an SQL query statement that returns a PHP object

global $wpdb;
$results = $wpdb->get_results( ‘SELECT * FROM wp_options WHERE option_id = 1’, OBJECT );

// 2nd Method – Utilizing the $GLOBALS superglobal. Does not require global keyword ( but may not be best practice )

$results = $GLOBALS[‘wpdb’]->get_results( ‘SELECT * FROM wp_options WHERE option_id = 1’, OBJECT );

The $wpdb object is not limited to the default tables created by WordPress; it can be used to read data from any table in the WordPress database (such as custom plugin tables). For example to SELECT some information from a custom table called “mytable”, you can do the following.


$myrows = $wpdb->get_results( "SELECT id, name FROM mytable" );