我可以使用此代码更新媒体:
function createMedia($urlImage , $title)
{
global $usernameWP;
global $passwordWP;
$rest_api_url = "https://www.example.com/wp-json/wp/v2/media";
// Obtenir le contenu de l'image
$image_data = file_get_contents($urlImage);
// Créer un nom de fichier à partir de l'URL
$filename = basename($urlImage);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $rest_api_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $image_data);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: image/png', // Ajouter le type de contenu de l'image
'Content-Length: ' . strlen($image_data),
'Content-Disposition: attachment; filename=' . $filename, // En-tête Content-Disposition
'Authorization: Basic ' . base64_encode($usernameWP . ':' . $passwordWP),
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resultJsonString = curl_exec($ch);
print_r($resultJsonString);
$resultJsonObject = null;
if ($resultJsonString)
{
$resultJsonObject = json_decode($resultJsonString);
}
else
{
logMessage("createPostWPWithRestAPI : no result");
}
curl_close($ch);
return $resultJsonObject;
}
但是如何指定一些字段,例如alt_text、caption呢?
发送 json_data 并在字段中指定 url 图像会更简单...
Stackoverflow 告诉我问题中的代码太多,所以我添加 blablablaStackoverflow 告诉我问题中的代码太多,所以我添加 blablabla Stackoverflow 告诉我问题中的代码太多,所以我添加了 blablabla
谢谢
如果您使用 WordPress 的媒体 REST API,“alt_text”和“caption”是您可以传递的参数,以便将它们包含在更新的媒体中,请参阅 WordPress 参考文档中的详细信息:https://developer。 wordpress.org/rest-api/reference/media/
这没有经过测试,但我认为这可以通过将curl_setopt设置为true,然后使用CURLOPT_POSTFIELDS来传递参数来实现,如下所示:
function createMediaWithCaptionAlt($urlImage , $title)
{
global $usernameWP;
global $passwordWP;
$rest_api_url = "https://www.example.com/wp-json/wp/v2/media";
// Obtenir le contenu de l'image
$image_data = file_get_contents($urlImage);
// Créer un nom de fichier à partir de l'URL
$filename = basename($urlImage);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $rest_api_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $image_data);
//New Code Here
$parameters = [
'caption' => __('A translateable string caption', 'your-text-domain'),
'alt_text' => __('A translateable Alt Text', 'your-text-domain'),
];
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: image/png', // Ajouter le type de contenu de l'image
'Content-Length: ' . strlen($image_data),
'Content-Disposition: attachment; filename=' . $filename, // En-tête Content-Disposition
'Authorization: Basic ' . base64_encode($usernameWP . ':' . $passwordWP),
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resultJsonString = curl_exec($ch);
print_r($resultJsonString);
$resultJsonObject = null;
if ($resultJsonString)
{
$resultJsonObject = json_decode($resultJsonString);
}
else
{
logMessage("createPostWPWithRestAPI : no result");
}
curl_close($ch);
return $resultJsonObject;
}