CentOSを使っています。php-xmlrpc(PHP XML-RPC)を使って、WordPressへ記事投稿をするためには次のようにします。
XML-RPCを使う処理の肝は、wpPostXMLRPC関数です。ここへ投稿する際のパラメータを渡す必要があるので、それを構築するcreateParam関数を用意しています。コンテンツの内容については、WordPressの記事と対応した値を設定する必要があるので、それを構築するcreateContent関数も用意しています。
<?php
$host = "localhost";
$xmlrpc_path = "/wp/xmlrpc.php";
$appkey = '';
$user = 'user';
$pass = 'pass';
$uri = "http://" . $host . $xmlrpc_path;
function createContent(
$title,
$body,
$keywords='',
$category,
$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, // 1:コメント許可
'mt_allow_pings'=>0, // 1:トラックバック許可
'post_type'=>'post',
'mt_keywords'=>$keywords,
'categories'=>array($category)
);
return $content;
}
function createParam(
$content,
$username,
$password,
$status=false
) {
$params = array(0, $username, $password, $content, $status);
return $params;
}
function wpPostXMLRPC($uri, $method, $params, $isXml) {
$request = xmlrpc_encode_request($method, $params);
$ch = curl_init(); // curl handle
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_URL, $uri);
curl_setopt($ch, CURLOPT_HEADER, false);
if ($isXml) {
// xmlデータ を受け取りたい場合
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
} else {
// entry id を受け取りたい場合
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
}
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
$results = curl_exec($ch);
curl_close($ch);
return $results;
}
$body = createContent(
"title 3",
"test text3.",
"未分類"
);
$param = createParam($user, $pass, true);
$method = 'metaWeblog.newPost';
$isXml = true;
$response = wpPostXMLRPC($uri, $method, $param, $isXml);
print_r($response);
?>
動作未確認ですが、classにするとしたら下記のような感じになるはずです。こちらの例では、CURLOPT_POSTのオプション指定を__callメソッド内で指定しています。xmlrpc_decode_request関数も使っています。なお、XMLで受けとるか、entry idで受けとるかの指定については省略をしてある、といった違いがあります。
public function __construct($uri) {
$this->uri = $uri;
$this->ch = null; // curl handle
}
public function __destruct() {
$this->close();
}
public function close() {
if ($this->ch !== null) {
curl_close($this->ch);
}
$this->ch = null;
}
public function __call($method, $params) {
$ch = $this->ch;
if ($ch === null) {
$this->ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->uri);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
}
$xml = xmlrpc_encode_request($method, $params);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
$response = curl_exec($ch);
$result = xmlrpc_decode_request($response, $method);
return $result;
}
}
XML-RPC wp « WordPress Codexも参考になるでしょう。
WordPress 3.0 関連書籍: