Bootstrapping WordPress MultiSite Outsite of WordPress – No $wpdb

I’m working on a plugin for a system to use WordPress as the authentication backend, so that I can use my existing WordPress users in another application. The plugin works great when running in single website mode:

include /path/to/wordpress/wp-config.php
global $wpdb;
// SQL and code to select user and compare entered passwords

I need this to work against a WordPress Multisite install as well. When I pull in the wp-config.php for the MS site, I end up with this error:

Fatal error: Call to a member function set_prefix() on a non-object in /path/to/wordpress/wp-includes/ms-settings.php on line 126

On line 126, WP is trying to set the table prefix against $wpdb, but for some reason $wpdb doesn’t exist here. I ran xdebug and $wpdb does get created, but ms-settings.php doesn’t see it. I can fix this by adding:

global $wpdb;

right before line 126 and it works, but I don’t want to modify the core WordPress code. Is there a better way to bootstrap WordPress ?

Solutions Collecting From Web of "Bootstrapping WordPress MultiSite Outsite of WordPress – No $wpdb"

You’ll want to include the wp-load.php, not the wp-config.php.

Depending on how you’re doing it, you may also have to set $_SERVER variables if they aren’t already set to prevent WordPress from trying to redirect you. For example:

$_SERVER = array(
  "HTTP_HOST" => "http://example.com",
  "SERVER_NAME" => "http://example.com",
  "REQUEST_URI" => "/",
  "REQUEST_METHOD" => "GET"
);

I think what you are experiencing is that you are trying to load WordPress from inside a method, function or call back that doesn’t have access to the global scope.

If WordPress is loaded outside of this – in my case ran with no errors.

Need to declare $wpdb global first, and then include wp-load.php:

global $wpdb;
require_once('/path/to/wordpress/wp-load.php');