嗨,请帮我解决从php代码创建新帖子的问题。
$access_token='XXXXXXXXXXXXXX';
$post = array('title=Hello World','content=Hello. I am a test post. I was created by the API','date='.date('YmdHis'),'categories=API','tags=tests');
$post = urlencode(implode('&',$post));
$apicall = "https://public-api.wordpress.com/rest/v1/sites/MYSITEID/posts/new";
$ch = curl_init($apicall);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('authorization: Bearer ' . $access_token,"Content-Type: application/x-www-form-urlencoded; charset=utf-8"));
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$return = curl_exec($ch);
echo "<pre>";
print_r($return);
exit;
结果为:
{"error":"unauthorized","message":"That API call is not allowed for this account."}
代码中是否有任何错误。 我在api控制台中检查过这个。 https://developer.wordpress.com/docs/api/console/它正在工作,但在代码中却无法正常工作
答案 0 :(得分:0)
他们准备$post
数据是完全错误的。您对整个内容进行了url-encode
,这就是为什么API服务器无法识别内容的原因。
将此$post
替换为:
$post = array(
'title'=>'Hello World',
'content'=>'Hello. I am a test post. I was created by the API',
'date'=>date('YmdHis'),
'categories'=>'API','tags=tests'
);
$post = http_build_query($post);
函数http_build_query
将自动对url-encode
数组中的内容执行$post
。