1. Understand the API
- Get the API documentation (base URL, endpoints, authentication method).
- Check if it uses REST or GraphQL.
- Note required API keys or tokens.
2. Choose Where to Integrate
You can integrate API calls in:
- Theme functions (
functions.php) - Custom plugin (recommended for reusability)
- Custom REST endpoint for AJAX/frontend usage
3. Make the API Request
WordPress provides HTTP functions:
wp_remote_get()for GET requestswp_remote_post()for POST requests
Example – GET request:
function get_weather_data() {
$response = wp_remote_get( 'https://api.example.com/weather?city=London', array(
'headers' => array(
'Authorization' => 'Bearer YOUR_API_KEY'
)
));
if ( is_wp_error( $response ) ) {
return 'Error fetching data';
}
$body = wp_remote_retrieve_body( $response );
return json_decode( $body, true );
}4. Display the Data
Example in a shortcode:
function display_weather_shortcode() {
$data = get_weather_data();
if ( isset( $data['temperature'] ) ) {
return 'Temperature: ' . esc_html( $data['temperature'] ) . '°C';
}
return 'No data available';
}
add_shortcode( 'weather', 'display_weather_shortcode' );Usage in a post/page:
[weather]5. Handle Authentication
- API Key in URL → Add as query parameter.
- Bearer Token → Use
Authorizationheader. - OAuth → Implement token retrieval & refresh logic.
6. Cache API Responses
External APIs may have request limits — use transients to store responses temporarily:
function get_cached_weather() {
$data = get_transient( 'weather_data' );
if ( false === $data ) {
$data = get_weather_data();
set_transient( 'weather_data', $data, HOUR_IN_SECONDS );
}
return $data;
}✅ Best Practices
- Sanitize & escape all output.
- Use caching to reduce API calls.
- Handle errors gracefully.
- Never expose API keys in public JS — call APIs from server-side PHP.
💡 Analogy:
Integrating an API into WordPress is like hiring a courier service — your site requests information from somewhere else, waits for the delivery, and then displays it to visitors.
