wp-config.php and standalone scripts

WordPress plugin architecture is great and it provides developers with a lot of flexibility.  But once in a while one needs to write a standalone script that should use some of WordPress settings.  For example, a script that would have the same database credentials as a WordPress instance.  This sounds simple unless you look at the bottom of the wp-config.php file.  There’s that:

/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');

That means if you are to include wp-config.php in your standalone script, you’ll get the whole WordPress thing loaded and fired up. On one hand, that’s cool because now you can use WordPress functions and objects. But on the other, it’s not. Sometimes you just need the configuration only.

The work around is trivial.  Modify wp-config.php file like so:

if (!defined('WP_CONFIG_ONLY')) {
    /** Sets up WordPress vars and included files. */
    require_once(ABSPATH . 'wp-settings.php');
}

Now, in your standalone scripts, you can do the following:

define('WP_CONFIG_ONLY', true);
require 'wp-config.php';

And you’ll only get WordPress configuration without any extras. If you don’t define the WP_CONFIG_ONLY constant before loading the wp-config.php, then all will work as before.

Leave a Comment