WP RestAPIを使って記事を投稿 PHP版

php-wp

WordPress Rest API を使って、PHPでデータの取得や、記事の投稿を行うサンプル。

 

全てのカテゴリーを取得する

$json = file_get_contents("https://sample.com/wp-json/wp/v2/categories?per_page=100&page=1");
$obj = json_decode($json,true);

    foreach ($obj as $category) {
        echo 'カテゴリー名: ' . $category['name'] . "(ID:" . $category['id'] . ')<br>';
    }

 

https://sample.com/wp-json/wp/v2/categories でも取得できるが、階層構造になっている場合に下層カテゴリが取得できない。

 

記事IDやスラッグから記事内容を取得

$url = "https://kazuoblog.net/wp-json/wp/v2/posts?slug=スラッグ";

$json = file_get_contents($url);
$obj = json_decode($json,true);

//slugから取得した場合のJSON処理
$content = $obj[0]['content']['rendered'];


//記事IDから取得した場合のJSON処理
//$content = $obj['content']['rendered'];


echo $content;


//HTMLタグを取り除くなら
$contents = strip_tags($content);

echo $contents;

 

記事を投稿する

$content =<<<EOM
<p>記事内容</p>
<p>記事内容</p>
EOM;


$data = [
	"title" => '記事のタイトル',
	"content" => $content,
	"slug" => '記事のスラッグ',
	"categories" => [8,10],
	"status" => "draft",
//	"status" => "publish",
//	"featured_media" => $media_id,
];


/*認証のためのヘッダ情報*/
$header = [
	'Authorization: Basic ' . base64_encode($username . ":" . $password),
	'Content-Type: application/json',
];

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $base_url.'wp-json/wp/v2/posts');
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST'); // post
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); 
curl_setopt($curl, CURLOPT_HTTPHEADER, $header); 
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);

$response = curl_exec($curl);

$header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);
$result = json_decode($body, true);

curl_close($curl);

$posts_id = '';
if (!empty($result)) {
	$posts_id = $result['id'];
}
echo "ID:" . $posts_id;

 

 メディアに画像をアップロードする

 

//フォームから
$file_name = $_FILES["addele01"]["tmp_name"];
$filename = $_FILES["addele01"]["name"];

//URLから
//$file_name = "http://admall.jp/img/logo.jpg";


$request_header = [
    'Authorization: Basic ' . base64_encode(sprintf('%s:%s', $username, $password)),
    sprintf('Content-Disposition: attachment; filename="%s"', $filename),
    'Content-Type: application/octet-stream',
];

/* URLから画像を取得(SSL対応)
$option = [];
$option['ssl'] = [];
$option['ssl']['verify_peer'] = false;
$option['ssl']['verify_peer_name'] = false;
*/

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $base_url.'wp-json/wp/v2/media');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($file_name));
//curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($file_name, false, stream_context_create($option)));
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

$media_id = '';
if (!empty($response)) {
	$media_id = json_decode($response, true)['id'];
}
echo "ID:" . $media_id;