Wordpress - Access WordPress API Outside of WordPress (command-line PHP)
WordPress expects the $_SERVER variables to be setup as if it were a normal web request. Also, I would suggest loading wp-load.php instead of wp-blog-header.php since you probably don't need the WP class or the template loader to run. Here is how I normally start any scripts I need to interact with WP from command line:
define('DOING_AJAX', true);
define('WP_USE_THEMES', false);
$_SERVER = array(
"HTTP_HOST" => "mysite.com",
"SERVER_NAME" => "mysite.com",
"REQUEST_URI" => "/",
"REQUEST_METHOD" => "GET"
);
require_once('current/wp-load.php');
Update 2018:
Nowadays Wordpress doesn't require $_SERVER at all. If you simply need to access Wordpress API functions (e.g. to read/write to the database), all you need is:
require_once('current/wp-load.php');
# your code goes here...
You can use the wp-cli eval-file
command:
@daily /usr/bin/wp --path=/path/to/wp/ eval-file /path/to/that_file.php
This will first load the WP environment, then run your file.