In questo articolo vedremo come creare un nuovo post su un blog WordPress usando REST API, in particolare vedremo come creare un nuovo media (foto) su WordPress sempre usando REST API, recuperare l'ID del media e associarlo al nuovo post che vogliamo creare.
In questo esempio verrà usata un'autenticazione di base, in particolare ad ogni richiesta verranno inviate le credenziali di accesso a WordPress, pertanto la prima operazione da fare è installare il plug-in Basic-Auth, per informazioni e su come installare e attivare questo plug-in consultare la seguente documentazione
Gli endpoints per creare un nuovo media e un nuovo post sono rispettivamente i seguenti
- https://<dominio-wordpress>/wp-json/wp/v2/media
- https://<dominio-wordpress>/wp-json/wp/v2/posts
dove 'dominio-wordpress' è il dominio del sito.
Come descritto nella documentazione REST API, per creare un nuovo media dobbiamo effettuare una richiesta di tipo POST all'endpoind indicato in precedenza, indicando nel corpo della richiesta i parametri richiesti obbligatori, ecco un esempio
<?php
$username = "<username-wp>";
$password = "<password-wp>";
// crea nuovo media
$url_media = "https://<dominio-wordpress>/wp-json/wp/v2/media";
$image = "https://url-image.jpg";
$file = file_get_contents($image);
$filename = time() . uniqid(rand()) . ".jpg";
try {
$ch_media = curl_init();
curl_setopt($ch_media, CURLOPT_URL, $url_media);
curl_setopt($ch_media, CURLOPT_POST, 1);
curl_setopt($ch_media, CURLOPT_POSTFIELDS, $file);
curl_setopt($ch_media, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch_media, CURLOPT_HTTPHEADER, [
'Content-Disposition: form-data; filename="' . $filename . '"',
"Authorization: Basic " . base64_encode($username . ":" . $password),
]);
$result_media = curl_exec($ch_media);
curl_close($ch_media);
$media = json_decode($result_media);
$id_media = $media->id;
echo "ID media item: " . $id_media . "\n";
} catch (PDOException $e) {
echo $e->getMessage();
}
$username e $password sono le credenziali di accesso a WordPress, $url_media è l'endpoint a cui inviare la richiesta di tipo POST ('dominio-wordpress' è il dominio del sito), $image è l'url dell'immagine, $file è il risultato della funzione file_get_contents() PHP al quale passiamo come parametro l'immagine ($image), $filename è il nome che vogliamo assegnare al nuovo media, in questo esempio ho generato un nome random tramite la funzione rand() PHP ma possiamo scegliere un nome qualunque, infine aggiungiamo all'header della richiesta un'autenticazione di base usando le credenziali di accesso usando una codifica base64 (base64_encode($username . ":" . $password), se la richiesta va a buon fine otteniamo l'ID del nuovo media tramite $media->id come nell'esempio.
A questo punto possiamo creare un nuovo post assegnadogli come immagine in evidenza quella corrispondente all'ID ottenuto in precedenza, e inserendo nel corpo della richiesta i parametri obbligatori come descritto nella documentazione REST API, anche in questo caso la richiesta è di tipo POST, ecco un esempio
<?php
// crea nuovo post
$url_post = "https://<dominio-wordpress>/wp-json/wp/v2/posts";
$slug = "laborum-eiusmod-officia-irure-non-et-labore-sunt";
$title = "Laborum eiusmod officia irure non et labore-sunt";
$category = 1;
$content = "Dolor consequat duis et officia ipsum elit non culpa consequat.";
$excerpt = "Dolor consequat duis et officia...";
$data = [
"slug" => $slug,
"status" => "publish",
"title" => $title,
"featured_media" => $id_media,
"categories" => $category,
"content" => "<!-- wp:paragraph -->
$content
<!-- /wp:paragraph -->",
"excerpt" => $excerpt,
];
$ch_post = curl_init();
curl_setopt($ch_post, CURLOPT_URL, $url_post);
curl_setopt($ch_post, CURLOPT_POST, 1);
curl_setopt($ch_post, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch_post, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch_post, CURLOPT_HTTPHEADER, [
"Authorization: Basic " . base64_encode($username . ":" . $password),
]);
$result_post = curl_exec($ch_post);
curl_close($ch_post);
$post = json_decode($result_post);
$id_post = $post->id;
echo "ID post item: " . $id_post . "\n";
$url_post è l'endpoint al quale inviare la richiesta, $slug è un identificatore univoco alfanumerico per il post, $title è il titolo del post, $category è l'id della categoria a cui appartiene il post, in questo esempio è 1, $content è il contenuto del post, $excerpt è un estratto del post, una descrizione breve per esempio, anche in questo caso aggiungiamo all'header della richiesta un'autenticazione di base usando le credenziali di accesso usando una codifica base64.
Ecco il codice completo
<?php
$username = "<username-wp>";
$password = "<password-wp>";
// crea nuovo media
$url_media = "https://<dominio-wordpress>/wp-json/wp/v2/media";
$image = "https://url-image.jpg";
$file = file_get_contents($image);
$filename = time() . uniqid(rand()) . ".jpg";
try {
$ch_media = curl_init();
curl_setopt($ch_media, CURLOPT_URL, $url_media);
curl_setopt($ch_media, CURLOPT_POST, 1);
curl_setopt($ch_media, CURLOPT_POSTFIELDS, $file);
curl_setopt($ch_media, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch_media, CURLOPT_HTTPHEADER, [
'Content-Disposition: form-data; filename="' . $filename . '"',
"Authorization: Basic " . base64_encode($username . ":" . $password),
]);
$result_media = curl_exec($ch_media);
curl_close($ch_media);
$media = json_decode($result_media);
$id_media = $media->id;
echo "ID media item: " . $id_media . "\n";
// crea nuovo post
$url_post = "https://<dominio-wordpress>/wp-json/wp/v2/posts";
$slug = "laborum-eiusmod-officia-irure-non-et-labore-sunt";
$title = "Laborum eiusmod officia irure non et labore-sunt";
$category = 1;
$content =
"Dolor consequat duis et officia ipsum elit non culpa consequat.";
$excerpt = "Dolor consequat duis et officia...";
$data = [
"slug" => $slug,
"status" => "publish",
"title" => $title,
"featured_media" => $id_media,
"categories" => $category,
"content" => "<!-- wp:paragraph -->
$content
<!-- /wp:paragraph -->",
"excerpt" => $excerpt,
];
$ch_post = curl_init();
curl_setopt($ch_post, CURLOPT_URL, $url_post);
curl_setopt($ch_post, CURLOPT_POST, 1);
curl_setopt($ch_post, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch_post, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch_post, CURLOPT_HTTPHEADER, [
"Authorization: Basic " . base64_encode($username . ":" . $password),
]);
$result_post = curl_exec($ch_post);
curl_close($ch_post);
$post = json_decode($result_post);
$id_post = $post->id;
echo "ID post item: " . $id_post . "\n";
} catch (PDOException $e) {
echo $e->getMessage();
}