Hey everyone, I’m hitting a wall trying to get data from an external REST API into my WordPress site. I’m using the Countries API, but I can’t seem to make it work.
I’ve set up Composer and added the Unirest PHP library. Here’s what my composer.json looks like:
But all I’m getting is a generic error message saying the site is having technical issues. Any ideas what I might be doing wrong? I’m pretty new to working with APIs in WordPress, so any help would be awesome!
I’ve encountered similar issues when integrating external APIs into WordPress. One thing to check is whether your WordPress installation is set up to allow external HTTP requests. Some hosts disable this by default for security reasons.
Try adding this line to your wp-config.php file:
define('WP_HTTP_BLOCK_EXTERNAL', false);
Also, ensure you’re using HTTPS for the API endpoint. If that doesn’t work, you might want to try using cURL instead of wp_remote_get(). Here’s a quick example:
hey mate, don’t forget to check ur API endpoint. sometimes the URL can be wrong or outdated. also, have u tried using a plugin like WP REST API? it can make things easier. if nothing works, maybe reach out to the API provider. they might have specific instructions for WP integration.
I’ve dealt with similar API integration headaches before. One thing that’s not immediately obvious is that WordPress has a built-in transients API, which can be a game-changer for external API calls. It allows you to cache the API responses, reducing load times and avoiding rate limiting issues.
Here’s a quick example of how you might implement this:
$transient_key = 'countries_api_data';
$country_data = get_transient($transient_key);
if (false === $country_data) {
$api_response = wp_remote_get('https://countries-api.example.com/v1/all', [
'headers' => [
'API-Host' => 'countries-api.example.com',
'API-Key' => 'my-secret-key-1234'
]
]);
if (!is_wp_error($api_response)) {
$country_data = json_decode(wp_remote_retrieve_body($api_response));
set_transient($transient_key, $country_data, HOUR_IN_SECONDS);
}
}
if ($country_data) {
// Use the data here
} else {
error_log('Failed to fetch country data from API');
}
This approach caches the API response for an hour, significantly reducing API calls. It’s been a lifesaver for me on several projects. Give it a shot and see if it helps with your integration!