Insert Post to WordPress via XML-RPC

Hello programmers!

I can’t count the days since the last time I added a post to my blog and here I am with a new post. This is about WordPress and XML-RPC.

Several days ago, I made a huge and gigantic mistake to the company’s server. I formatted the disk. Oh my God! How dumb I was for not reading the instruction thoroughly. The consequence, I erased some critical scripts which had been used to pull content and saved it to the database. Fortunately, I didn’t erased any critical data. Well, there will always a bright side in every trouble, right?

So what did I do? Of course, I rewrote the scripts. Those scripts are not mine, but at least, I get the logic of it. It’s actually read some XML files, parse it, insert it to a WordPress database through XML-RPC, and delete all the XML files. Easy right?Before I started writing the code, I need to install a PHP module (php-xmlrpc). Since my server OS is CentOS, so this command will do it:

yum install php5-xmlrpc

That’s enough, now let’s get into the code. First, I made a class named xmlrpc.class.php and this is the code:

<?php class WP_XMLRPCClient { 	
  var $xmlrpcurl; 	
  var $username; 	
  var $password; 	

  public function __construct($xmlrpcurl, $username, $password) { 		
    $this->xmlrpcurl = $xmlrpcurl;
    $this->username = $username;
    $this->password = $password;
  }

  public function send_request($requestname, $params) {
    $request = xmlrpc_encode_request($requestname, $params);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
    curl_setopt($ch, CURLOPT_URL, $this->xmlrpcurl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 1);
    $results = curl_exec($ch);
    curl_close($ch);
    return $results;
  }

  public function create_post($title, $body, $category, $keywords='', $encoding='UTF-8') {
    $title = htmlentities($title, ENT_NOQUOTES, $encoding);
    $keywords = htmlentities($keywords, ENT_NOQUOTES, $encoding);

    $content = array(
      'title'=>$title,
      'description'=>$body,
      'mt_allow_comments'=>0,
      'mt_allow_pings'=>0,
      'post_type'=>'post',
      'mt_keywords'=>$keywords,
      'categories'=>array($category)
    );

    $params = array(0, $this->username, $this->password, $content, true);

    return $this->send_request('metaWeblog.newPost', $params);
  }
}

The idea of posting data through XML-RPC is sending a set of parameters to a wordpress xmlrpc class with xmlrpc request. From the code above, you can see what kind of parameters that I want to send. It’s defined in the function create_post with variable $content. The complete list of parameter that you can use is defined in this page.

Now, let’s create a script to execute the logic. This is the code that I wrote:

<?php 
include_once('xmlrpc.class.php'); 
date_default_timezone_set('Asia/Jakarta'); 
$files = array(); 
$directory = '/location/to/a/folder'; 
$xmlrpc_obj = new WP_XMLRPCClient('http://your-wordpress-site.com/xmlrpc.php', 'wp-user-username', 'wp-user-password'); 
$category = 'WP Category'; 

$files = open_dir($directory); 
read_and_post($directory, $files, $category, $xmlrpc_obj); 
exit; 

function open_dir($directory) {   
  if (is_dir($directory)) {     
    $temp_arr = array();     
    $handle = opendir($directory);     
    while (false !== ($entry = readdir($handle))) {       
      if ($entry != "." && $entry != ".." && $entry[0] != '.') {       
        array_push($temp_arr, $entry);       
      }     
    }     

    return $temp_arr;   
  } else {     
    exit;   
  } 
} 

function read_and_post($directory, $files, $category, $xmlrpc_obj) {   
  foreach($files as $file) {     
    $content_from_body = true;     
    $xml_file = $directory . '/' . $file;     
    $xml = simplexml_load_file($xml_file); // I intended to load an XML file and parse it     

    /* ... create your $title and $content here ... */     
    $xmlrpc_obj->create_post($title, $content, $category);

    /* unlink file */
    unlink($xml_file);
  }

  rmdir($directory);
}

That’s the code and you just need to execute it via terminal with php command.

I’m still questioning about how to add a new post through XML-RPC with predefine post_date. I’ve tried the parameter according to wordpress page, but it results nothing. Either, it uses the insertion time or it doesn’t insert the post at all. I’m still trying to figure it out.

Anyway, happy coding!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s