Using wpdb, the WordPress database, outside of WordPress

Occasionally it may be useful to have a dynamic page outside of WordPress that can still access the $wpdb object. If you search around the internet, you’ll eventually find that loading the wp-load script (example below) will make the database object available to you.

Old Way

require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );

One problem with that solution is that it loads ALL the overhead of WordPress, which may be what you want if you need to use “The Loop” in your page, but usually isn’t what I’m looking for. If you’re using a caching plugin like W3TC to speed up your site, you’ll notice that including wp-load triggers W3TC to take over your page, which can give unexpected results. To work around this, I now set up the database using the few lines below.

New Way

define( 'BLOCK_LOAD', true );
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-config.php' );
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-includes/wp-db.php' );
$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);

This does require one small change to the wp-config file to add support for blocking it from loading the rest of WordPress. You’ll need to find the line in the file that includes wp-settings and change it to look like the line below. In normal WordPress usage it will continue to include the wp-settings file as before, but in our special case, it will stop and only load the database settings.

if ( !( defined('BLOCK_LOAD') && BLOCK_LOAD ) ) require_once(ABSPATH . 'wp-settings.php');

NOTE: You may have to edit the paths above to reference the proper location of your WordPress install.

UPDATE

WordPress 3.4 broke this method, but I have a new method.