WordPress command line PHP

This is a quick overview on running a PHP file via the command line, bootstrapped within the WordPress ecosystem. This sounds like a mouthful, but it’s a fairly straight forward concept. Let’s suppose you have a requirement, where you need to run a PHP script as a one off, or even regularly as a cron job (let’s forgot about WP cron for a moment). The specifc use-case I find arising again and again, is where I need to import data from another source into WordPress. Perhaps the data I’m getting is in a really weird format, from a legacy system, needs to go into a custom system, or a host of other reasons why imports may not already exist for your use-case. This file will need to be run directly, through the command line, on ocassion – not through your admin, not as a page on your WordPress site, how do we achieve this?

We need to consider the fact this script shouldn’t load all of WordPress. We want access to WordPress core functionality, but we don’t want WordPress to parse the file like it does a URL, and we don’t want it to run a WordPress query. So first we disable themes using define. Secondly, we include wp-load.php.

define( 'WP_USE_THEMES', false );
require( dirname(__FILE__) . '/wp-load.php' );

It’s important to note the wp-load.php path will have to be relative to where you PHP file is. I’ve put my PHP file in the theme folder, because the importer I’m writing is directly tied to the theme. As such my require statement is:

require(dirname(__FILE__) . '/../../wp-load.php');

In essence, this is all that is really needed. Putting this at the top of the file will allow you to utilise all of WordPress’ comprehensive supportive functions. We can make this a bit nicer, add in some extra checks if we like, but put this into the head of your file and you’re good.

At the beginning of your script, you could also check to see if the file is being run from the command line, to stop unwanted web requests from triggering your process. Full snippet below, including utilising the WordPress DB object:

<?php
if(php_sapi_name() !== 'cli') {
    die("Meant to be run from command line");
}

define('WP_USE_THEMES', false);

require(dirname(__FILE__) . '/../../../../wp/wp-load.php');

global $wpdb;

$query = <<<PRE
SELECT *
FROM $wpdb->posts
WHERE post_type = 'post'
AND post_status = 'publish'
PRE;

$results = $wpdb->get_results($query);

var_dump($results);

Published by

MHayward

I am a Web Developer who has been creating websites and hacking at WordPress for over 4 years. I'm a graduate of Surrey University where I studied Computer Science.

Find me on linked in http://uk.linkedin.com/in/mhayward89