php

XML-RPC を利用してwordpressに記事を投稿する

必要なライブラリをダウンロード

XML-RPCを利用するのに必要なライブラリをダウンロードして、インクルードします。

IXR_Library.phpをダウンロード

[php]include_once("IXR_Library.php");
$client=new IXR_Client("http://wordpress-domain.com/xmlrpc.php");[/php]

新規投稿の設定

[php] $wp_username="WP-USERNAME";
$wp_password="WP-PASSWORD";

$postdate = new IXR_Date(mktime(0,0,0,4,20,2017));
$gmtpostdate = new IXR_Date(mktime(0,0,0,4,20,2017));

$url = "http://~~";

$status = $client->query( ‘metaWeblog.newPost’,
”,
$wp_username,
$wp_password,
array(
‘title’ => $title,
‘description’ => $description,
‘dateCreated’ => $postdate,
‘date_created_gmt’ => $gmtpostdate,
// その他、カスタムフィールド、アイキャッチ、タグなどをここで設定可能①
‘post_status’ => ‘publish’
),
2); // 0:下書き 1:公開 2:予約投稿

if($status){ echo "成功";}
else{ echo $client->getErrorMessage();}[/php]

カスタムフィールドなどを設定する

上のコードの①のあたりに追加します。アイキャッチの場合はメディアIDを指定します。

設定出来るパラメータはこちらで確認出来ます。
XML-RPC MetaWeblog API

[php]
//カスタムフィールドを設定する
"custom_fields" => array(
array( "key" => "url", "value" => $url ),
),
//タグを設定する
‘mt_keywords’ => array(‘tag1’, ‘tag2’, ‘tag3’),

//アイキャッチを設定する
‘wp_post_thumbnail’ => $img["id"],[/php]

画像のアップロード

[php]
$thumbnail_url = "http://~~~~.png";

$filename = pathinfo( $thumbnail_url );
$filename = $filename["basename"];
$imgInfo = getimagesize($thumbnail_url);
$type = $imgInfo["mime"];

$bits = new IXR_Base64(file_get_contents($thumbnail_url));
$status1 = $client->query(
"wp.uploadFile",
1,
$wp_username,
$wp_password,
array(
"name" => $filename,
"type" => $type,
"bits" => $bits,
"overwrite" => false,
"post_id" => $post_id
)
);
$img = $client->getResponse();
echo $client->getErrorMessage();

投稿した画像のメディアIDを取得
$media_id = $img["id"];

[/php]