1,208 Views
Sure, here’s an example of how you might use PHP cURL to make a request to the WordPress REST API, along with some error handling:
<?php
// Endpoint URL
$endpoint = 'https://your-wordpress-site.com/wp-json/wp/v2/posts';
// Data to send in the request
$data = array(
'title' => 'Hello World',
'content' => 'This is a test post created via REST API.'
);
// Initialize cURL session
$ch = curl_init();
// Set cURL options
curl_setopt_array($ch, array(
CURLOPT_URL => $endpoint,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
// Add any additional headers if needed, such as authentication headers
)
));
// Execute the request
$response = curl_exec($ch);
// Check for errors
if ($response === false) {
// Handle cURL error
echo 'cURL error: ' . curl_error($ch);
} else {
// Decode the response
$result = json_decode($response, true);
// Check if response contains error message
if(isset($result['code']) && isset($result['message'])){
echo 'WordPress API Error: ' . $result['message'];
} else {
// Request was successful
echo 'Post created successfully. ID: ' . $result['id'];
}
}
// Close cURL session
curl_close($ch);
?>
Make sure to replace 'https://your-wordpress-site.com/wp-json/wp/v2/posts'
with the actual endpoint URL you want to access, and adjust the data being sent in the $data
array according to your needs. Also, ensure that you handle any authentication required by your WordPress site, such as including authentication headers in the CURLOPT_HTTPHEADER
array.