WordPress in command line scripts

Though WordPress has wp-cron functionality to do scheduled tasks, I still like Unix crontab to do them. Fortunately, we can write script programs in PHP to run from a command line even if the scripts call WordPress functions. To do WordPress operation in a script, we have to include ‘wp-load.php’ before the operation.

Below is a sample script to create a new post. You can run it from a command line. Before loading ‘wp-load.php’, you have to set PHP ‘$_SERVER’ variable. Especially in a multisite environment, WordPress will determine which site to involve by $_SERVER values.

#!/usr/bin/php
<?php

// define('WP_DEBUG', true); /* uncomment for debug */

$_SERVER = array(
  "HTTP_HOST" => "en.hetarena.com",
  "SERVER_NAME" => "en.hetarena.com",
  "REQUEST_URI" => "/",
  "REQUEST_METHOD" => "GET"
);

// you may have to change directory path
require_once('/usr/share/wordpress/wp-load.php');

$post = array (
  'post_content'   => 
    "<p>Hello, World!</p>",
  'post_type'      => 'post',
  'comment_status' => 'closed',
  'ping_status'    => 'closed',
  'post_status'    => 'publish',
  'post_author'    => 2,
  'post_title'     => 'My post',
  'post_category'  => array(1)
);
$e = wp_insert_post($post, true);
if (is_wp_error($e)) {
  print $e->get_error_message();
}
else {
  print "Post ID = " . $e . "\n";
}

I’ve learned this method from this site, but I have to remove protocol strings from $_SERVER to make it work.

Leave a Reply

Your email address will not be published. Required fields are marked *


*