我已经使用带有CURL的wordpress REST API完成了核心PHP应用程序中列出的所有页面,但是我无法用CURL删除那些页面。我收到了消息" {code:" rest_cannot_delete" ,消息:"抱歉,您不能删除此帖子。}"每次。
这是我的代码。
$url = 'http://localhost/wordpress/wp-json/wp/v2/pages/37';
$postdata = 37; //pageID
function callrestapi_curlDelete($url, $postdata) {
$postdata_json = json_encode($postdata);
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
));
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata_json);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
echo json_decode($resp, TRUE);
}
或者,如果我尝试使用此代码,则会收到相同的错误。
$.ajax({
url: 'http://localhost/wordpress/wp-json/wp/v2/pages/15 ',
method: 'DELETE',
crossDomain: true,
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'Authorization', 'Basic ' + Base64.encode('admin:admin@123'));
},
success: function( data, txtStatus, xhr ) {
console.log( data );
console.log( xhr.status );
}
});
答案 0 :(得分:1)
无需发布任何数据来删除页面/帖子。该URL已足够,因为您已包含要删除的ID。见下面的例子:
$postid = 108;
$rest_api_url = "http://www.example.com/wp-json/wp/v2/post/".$postid;
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_URL, $rest_api_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer '.$token,
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
注意授权的变量$ token,我假设您已经知道如何通过基本身份验证生成。
这会将帖子置于垃圾箱中,如果您想永久删除,请将以下内容添加到您的网址末尾。
?force=true
答案 1 :(得分:0)
将此行添加到您的cURL代码
curl_setopt($ch, CURLOPT_USERPWD, "username" . ":" . "password");
不要忘记安装和激活基本的auth主插件