WordPress API Integration: A Practical Guide with Contact Form 7 (JSON Example)

Looking to connect your WordPress site to external services—like CRMs, marketing platforms, or internal tools? This guide explains WordPress API integration in clear terms and walks through a real-world example: sending Contact Form 7 submissions to an external API as a JSON object. We’ll cover how it works, the moving parts involved, and provide a production-minded code sample to get you started.
Caveat: The code below is for demonstration only. Please do not use it on a live site without first implementing and testing it on a staging environment and having a developer review it for your specific use case.
What is API integration in WordPress?
An API (Application Programming Interface) lets different systems exchange data. In WordPress, common use cases include:
- Sending data out – e.g. pushing lead data to a CRM or sales platform.
- Pulling data in – e.g. fetching inventories, prices, or content from third-party services.
- Automating workflows – e.g. tagging contacts, creating tickets, or triggering webhooks.
Done properly, WordPress API integration helps your site work seamlessly with the rest of your tech stack.
Key building blocks for WordPress API integrations
- Authentication
Most APIs require API keys, bearer tokens, or OAuth. Store secrets securely (e.g. inwp-config.php
or environment variables) and avoid hard-coding them in public files. - The WordPress HTTP API
Usewp_remote_post
/wp_remote_get
for requests. It handles SSL, errors, and proxies better than raw cURL. - JSON payloads
Modern APIs use JSON. Build payloads withwp_json_encode
and parse responses withjson_decode
. - Hooks & architecture
For Contact Form 7, hooks likewpcf7_mail_sent
are ideal. Prefer a small plugin over theme snippets so your integration is portable and version-controlled. - Error handling & logging
Check response codes, log failures, and add observability (admin logs or a logging library) so issues can be diagnosed. - Security & data protection
Sanitise input, validate responses, and consider GDPR when sending personal data to third parties.
Example: Contact Form 7 API integration (send JSON to an external endpoint)
The following plugin listens for successful Contact Form 7 submissions and posts the data as JSON to your chosen API endpoint. Replace field names, endpoint URL, and authentication to match your requirements.
File path: wp-content/plugins/cf7-to-api-integration/cf7-to-api-integration.php
<?php
/**
* Plugin Name: CF7 to External API (JSON)
* Description: Posts Contact Form 7 submissions to an external API in JSON format using the WP HTTP API.
* Version: 1.0.0
* Author: Your Name
*/
if ( ! defined( 'ABSPATH' ) ) exit;
/**
* Configuration: set your endpoint and auth here or load from env/DB.
* For production, prefer storing secrets in wp-config.php or environment variables.
*/
define( 'CF7_API_ENDPOINT', 'https://api.example.com/v1/leads' ); // <-- Your API endpoint
define( 'CF7_API_TOKEN', 'YOUR_BEARER_TOKEN_HERE' ); // <-- Store securely in practice
/**
* Hook into CF7 after mail is sent.
* Alternatives: wpcf7_before_send_mail (fires earlier), wpcf7_submit (fires even if mail fails).
*/
add_action( 'wpcf7_mail_sent', function( $contact_form ) {
// Get the submission instance
$submission = WPCF7_Submission::get_instance();
if ( ! $submission ) {
return; // Nothing to do
}
// Posted form data (keys are CF7 field names)
$posted_data = $submission->get_posted_data();
// Optional: limit this integration to a specific form
$target_form_id = 1234; // <-- Replace with your CF7 form ID or remove this check to run for all
if ( (int) $contact_form->id() !== (int) $target_form_id ) {
return;
}
/**
* Map CF7 fields to your API schema.
* Example CF7 field names: your-name, your-email, your-phone, your-message
* Adjust to match your form and the external API’s expected payload.
*/
$payload = [
'fullName' => isset( $posted_data['your-name'] ) ? sanitize_text_field( $posted_data['your-name'] ) : '',
'email' => isset( $posted_data['your-email'] ) ? sanitize_email( $posted_data['your-email'] ) : '',
'phone' => isset( $posted_data['your-phone'] ) ? sanitize_text_field( $posted_data['your-phone'] ) : '',
'message' => isset( $posted_data['your-message'] ) ? sanitize_textarea_field( $posted_data['your-message'] ) : '',
'source' => 'Contact Form 7',
'pageUrl' => isset( $_SERVER['HTTP_REFERER'] ) ? esc_url_raw( $_SERVER['HTTP_REFERER'] ) : home_url(),
'utm' => [
'utm_source' => isset( $_COOKIE['utm_source'] ) ? sanitize_text_field( $_COOKIE['utm_source'] ) : '',
'utm_medium' => isset( $_COOKIE['utm_medium'] ) ? sanitize_text_field( $_COOKIE['utm_medium'] ) : '',
'utm_campaign' => isset( $_COOKIE['utm_campaign'] ) ? sanitize_text_field( $_COOKIE['utm_campaign'] ) : '',
],
// Example consent flag if you have a checkbox named "consent"
'consent' => ! empty( $posted_data['consent'] ) ? true : false,
];
// Build the HTTP args
$args = [
'timeout' => 10,
'redirection' => 3,
'blocking' => true,
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
// Example Bearer auth. Use whatever your API expects.
'Authorization' => 'Bearer ' . CF7_API_TOKEN,
],
'body' => wp_json_encode( $payload ),
];
// Send POST request
$response = wp_remote_post( CF7_API_ENDPOINT, $args );
// Handle errors
if ( is_wp_error( $response ) ) {
error_log( '[CF7->API] HTTP Error: ' . $response->get_error_message() );
return;
}
$code = wp_remote_retrieve_response_code( $response );
$body = wp_remote_retrieve_body( $response );
// Basic success check (adjust to your API’s response contract)
if ( $code >= 200 && $code < 300 ) {
// Optional: parse/log or trigger follow-up actions
// $data = json_decode( $body, true );
// error_log( '[CF7->API] Success: ' . $body );
} else {
error_log( sprintf( '[CF7->API] Non-2xx response (%d): %s', $code, $body ) );
}
} );
Matching Contact Form 7 fields
Example CF7 form with fields matching the code above:
[text* your-name placeholder "Your Name"]
[email* your-email placeholder "Your Email"]
[tel your-phone placeholder "Your Phone"]
[textarea your-message placeholder "Your Message"]
[checkbox consent use_label_element "I agree to the privacy policy."]
[submit "Send"]
Tip: Find a form’s numeric ID under Contact → Contact Forms (hover the form name).
How the Contact Form 7 API integration works (step-by-step)
- User submits the CF7 form → CF7 validates fields and triggers its workflow.
- Hook fires → The plugin listens on
wpcf7_mail_sent
and captures$submission->get_posted_data()
. - Sanitise & map → Field values are sanitised and mapped to your external API’s expected JSON structure.
- HTTP POST → The plugin sends JSON to the API endpoint using
wp_remote_post
(the WordPress HTTP API). - Handle responses → Check status codes, log errors, and add observability as needed.
Best practices for reliable WordPress API integrations
- Secrets management: Move tokens to
wp-config.php
or environment variables; never commit secrets to Git. - Robust error handling: Log failures with enough context to diagnose issues later.
- Retry strategy: If the third-party API is down, queue payloads (custom table or transients) and retry via WP-Cron.
- Per-form settings: For multiple forms, add a settings page or integration panel to manage endpoints and field mappings.
- Privacy & consent: Update your privacy policy and capture consent when sending personal data to external services.
Quick example: Pull data into WordPress via an API (GET)
Fetching data is as common as sending it. Here’s a minimal pattern using the WordPress HTTP API:
$response = wp_remote_get( 'https://api.example.com/v1/products?limit=10', [
'timeout' => 10,
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . YOUR_API_TOKEN,
],
] );
if ( ! is_wp_error( $response ) && wp_remote_retrieve_response_code( $response ) === 200 ) {
$data = json_decode( wp_remote_retrieve_body( $response ), true );
// Render $data in a shortcode, block, or template.
}
Frequently Asked Questions about WordPress API Integration
How do I integrate an API with WordPress?
You can integrate an API with WordPress by using the WordPress HTTP API functions such as wp_remote_post
and wp_remote_get
. These allow you to send and receive JSON data securely, using authentication tokens or API keys where required. Typically, you’ll build a small plugin or use a theme function to manage the connection.
Can I send Contact Form 7 submissions to an external API?
Yes. Contact Form 7 provides hooks like wpcf7_mail_sent
that let you capture form data once a user submits the form. From there, you can map the fields to your API’s JSON schema and send them to an external service using wp_remote_post
. This makes Contact Form 7 API integration straightforward and reliable.
What is the difference between a webhook and an API call in WordPress?
A webhook is an automated message sent from one system to another when an event occurs, for example when a form is submitted. An API call is a request that your WordPress site actively makes to an external service, such as sending form data or fetching product information. Both approaches are common in WordPress API integrations.
Can I use OAuth 2.0 when integrating APIs in WordPress?
Yes. Many APIs use OAuth 2.0 for secure authentication. In WordPress, you’ll typically request and store an access token, then include it in your HTTP request headers. You may also need to refresh the token periodically, which can be handled via a scheduled task (WP-Cron) or a plugin helper library.
Is Contact Form 7 the best plugin for API integrations?
Contact Form 7 is a popular choice because of its simplicity and useful hooks, making it easy to push data to external APIs. However, for more advanced workflows you may also want to consider plugins like Gravity Forms or WPForms, which offer built-in API add-ons. The best choice depends on your project requirements.
Important note before you go live
Do not deploy these snippets straight to production. Implement and test on a staging site first, ensure data protection requirements are met, and have a developer review performance, security, and error handling for your exact scenario.
Need some help?
Need some help integrating an API to your site? Contact us and our friendly team would be happy to discuss your project API requirements with you.