PHP cURL调用WordPress REST API获取分类报rest_missing_callback_param错误
问题原因及解决方法
核心错误
你调用WordPress REST API获取分类时用了POST请求,但/wp/v2/categories接口的GET方法才是用来查询分类列表的,POST方法是创建新分类的接口,而创建分类必须传name参数,这就是你收到rest_missing_callback_param错误的直接原因。
修复步骤
1. 把请求方法改成GET
修改curlExecute函数,将POST请求改为GET,同时把参数拼接到URL上,而不是放在POST请求体里:
function curlExecute($url, $headers, $data = null) { $ch = curl_init(); // 有参数的话拼接成URL查询字符串 if ($data) { $url .= '?' . http_build_query($data); } curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, false); // 改为GET请求 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); return $response; }
2. 移除多余请求头
GET请求不需要发送JSON请求体,删掉Content-Type: application/json这个头:
$headers = array( 'Authorization: Basic ' . base64_encode($username.":".$applicationPassword) );
3. 调整per_page参数
WordPress REST API默认per_page最大值是100,设成9999会被自动截断成100。如果要获取所有分类,要么分页请求,要么通过WordPress过滤器rest_post_collection_params修改最大值。
修正后的完整代码
<?php include 'db-connect.php'; $conn = OpenCon(); $conn->set_charset("utf8"); $siteId = $_REQUEST["site-id"]; $sqlWebsite = "SELECT setting_value FROM ai_settings WHERE id = ".$siteId; $queryWebsite = mysqli_query($conn, $sqlWebsite); $rowWebsite = mysqli_fetch_row($queryWebsite); $websiteArray = json_decode($rowWebsite[0]); $site_url = "https://" . $websiteArray->url; $username = $websiteArray->user; $applicationPassword = $websiteArray->pass; $categoriesEndpont = $site_url . '/wp-json/wp/v2/categories'; $headers = array( 'Authorization: Basic ' . base64_encode($username.":".$applicationPassword) ); $data = array( 'per_page' => 100 // 使用默认最大值,或按需调整 ); // 获取分类 $categoriesResponse = curlExecute($categoriesEndpont, $headers, $data); print_r($categoriesResponse); function curlExecute($url, $headers, $data = null) { $ch = curl_init(); if ($data) { $url .= '?' . http_build_query($data); } curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, false); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); return $response; } ?>
内容的提问来源于stack exchange,提问作者VORiAND
相关产品推荐
相关产品推荐

