Hello. In this article, we will learn how to read data from the WordPress Media Manager via API. The distinguishing feature of today’s post is that we’ll use native PHP CURL functions instead of the WP wrapper “wp_remote_get(...)”.
A request to the URL “/wp-json/wp/v2/media/” does not require any authentication (just like retrieving posts via API).
All we need to do is send a GET request to “my-site/wp-json/wp/v2/media/” and receive the response in JSON format.
You can verify this without any PHP code — just enter the URL into your browser’s address bar. The site will return a JSON response.
If you’re using Firefox, the data will be nicely formatted. If you’re using Chrome, I recommend installing the “JSONView” extension or similar. I don’t use other browsers.
Now back to the code. Below is a full working example:
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => мой-сайт/wp-json/wp/v2/media/',
CURLOPT_RETURNTRANSFER => true,
]);
$exec = curl_exec($ch);
$getinfo_ar = curl_getinfo($ch);
if(empty($getinfo_ar['http_code']) || $getinfo_ar['http_code'] != 200)
{
echo 'Failed to retrieve data';
die;
}
$json_ar = json_decode($exec, true);
echo "<pre dir='ltr'>\$json_ar = ";print_r($json_ar); echo "</pre>";
curl_close($ch);We can conventionally break this code into three parts:
- Data retrieval
- Validation
- Display
Data retrieval
$ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_URL => мой-сайт/wp-json/wp/v2/media/', CURLOPT_RETURNTRANSFER => true, ]); $exec = curl_exec($ch); $getinfo_ar = curl_getinfo($ch);
Using a set of CURL functions, we form a request to get data via the WordPress API.
The function “curl_setopt_array(...)” allows us to configure the request parameters via an array, which is very convenient.
You can get the result of a CURL request via:
curl_exec(...) — response body
curl_getinfo(...) — response headers
Validating the response
if(empty($getinfo_ar['http_code']) || $getinfo_ar['http_code'] != 200)
{
echo 'Failed to retrieve data';
die;
}The check here is simple: if the response code is missing or not equal to 200 (OK), something went wrong — so we output a message or throw an exception.
Displaying the data
In our case, we simply output the data on screen for testing purposes.
$json_ar = json_decode($exec, true); echo "<pre dir='ltr'>\$json_ar = ";print_r($json_ar); echo "</pre>"; curl_close($ch);
And finally, we close the CURL connection.
