惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 司徒正美
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
美团技术团队
WordPress大学
WordPress大学
罗磊的独立博客
Last Week in AI
Last Week in AI
人人都是产品经理
人人都是产品经理
爱范儿
爱范儿
MongoDB | Blog
MongoDB | Blog
J
Java Code Geeks
H
Hackread – Cybersecurity News, Data Breaches, AI and More
H
Help Net Security
S
SegmentFault 最新的问题
C
Check Point Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
腾讯CDC
Engineering at Meta
Engineering at Meta
The GitHub Blog
The GitHub Blog
F
Fortinet All Blogs
D
DataBreaches.Net
雷峰网
雷峰网
GbyAI
GbyAI
宝玉的分享
宝玉的分享

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Why Your wp_remote_post Isn't Sending CF7 Data to Your AP...
Rahul Sharma · 2026-05-20 · via DEV Community

Why Your wp_remote_post Isn't Sending CF7 Data to Your API (And How to Fix It)<br>
A developer posted this exact problem on the WordPress support forums: they followed a YouTube tutorial step-by-step, hooked into wpcf7_before_send_mail, built a wp_remote_post call and nothing arrived at the external API. No errors, no data, just silence.
This is more common than you'd think. Let's dissect exactly what went wrong in that code and how to fix it with a no-code alternative at the end if you'd rather skip the debugging rabbit hole.

The Original Code (And What's Broken In It)
Here's the code from the forum post, cleaned up for readability:

add_action( 'wpcf7_before_send_mail', 'blog_cf7_api_sender' );

function blog_cf7_api_sender( $contact_form ) {
    $form_id = ( $contact_form )->id();

    if ( $form_id == '02d6ca7' ) {
        $submission = WPCF7_Submission::get_instance();

        if ( $submission ) {
            $posted_data = $submission->get_current();

            $name        = $posted_data['client-name'];
            $phone       = $posted_data['client-phone'];
            $stream_code = [4yv1];   // ← syntax error
            $token       = [12345];  // ← this is an array, not a string

            $url = 'https://coolapi.com';

            $args = array(
                'body' => json_encode(array(
                    'name'        => $name,
                    'phone'       => $phone,
                    'stream_code' => $stream_code,
                    'token'       => $token,
                )                    // ← missing closing parenthesis for json_encode
                'headers' => array(
                    'Authorization' => 'Bearer $token',  // ← single quotes = literal string
                    'Content-Type'  => 'application/json',
                )
            );

            $response = wp_remote_post( $url, $args );
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

There are five bugs in this snippet. Let's go through each one.

Bug 1: [4yv1] Is Not Valid PHP

$stream_code = [4yv1];

Enter fullscreen mode Exit fullscreen mode

PHP's short array syntax [] expects valid expressions inside. 4yv1 is neither a string, integer, nor a variable it's a bare word starting with a digit, which is a parse error. This would cause a fatal PHP error before wp_remote_post ever gets called.

Fix:

$stream_code = '4yv1'; // string
// or if it's meant to be a variable: $stream_code = $some_variable;

Enter fullscreen mode Exit fullscreen mode

Bug 2: $token Is an Array, Not a String

$token = [12345];

Enter fullscreen mode Exit fullscreen mode

This creates a PHP array [12345], not the integer or string 12345. When you later try to interpolate it into a Bearer header, it won't behave as expected.

Fix:

$token = '12345'; // string token

Enter fullscreen mode Exit fullscreen mode

Bug 3: Missing Closing Parenthesis for json_encode()

$args = array(
    'body' => json_encode(array(
        'name'  => $name,
        'phone' => $phone,
    )              // ← closes the inner array(), but json_encode() is never closed
    'headers' => ...

Enter fullscreen mode Exit fullscreen mode

The json_encode() call is never closed with ) before the comma. This is another parse error.

Fix:

'body' => json_encode(array(
    'name'  => $name,
    'phone' => $phone,
)),  // ← closes json_encode() AND the 'body' key

Enter fullscreen mode Exit fullscreen mode

Bug 4: 'Bearer $token' in Single Quotes

'Authorization' => 'Bearer $token',

Enter fullscreen mode Exit fullscreen mode

In PHP, single-quoted strings do not interpolate variables. This sends the literal string Bearer $token to the API not the token value.

Fix:

'Authorization' => 'Bearer ' . $token,
// or with double quotes:
'Authorization' => "Bearer $token",

Enter fullscreen mode Exit fullscreen mode

Bug 5: The Hook Only Fires When Email Sending Is Active

This was the only hint from the WordPress forum moderator, but it's worth expanding on. wpcf7_before_send_mail is triggered as part of the mail-sending pipeline. If your CF7 form has email sending disabled (or the form tag doesn't have a mail configuration), this hook never fires silently.

You can verify this quickly:

add_action( 'wpcf7_before_send_mail', function( $contact_form ) {
    error_log( 'Hook fired for form: ' . $contact_form->id() );
});

Enter fullscreen mode Exit fullscreen mode

Check your server logs. If nothing appears, email sending isn't active for that form.

Alternative hook that always fires regardless of mail settings:

add_action( 'wpcf7_submit', 'blog_cf7_api_sender', 10, 2 );

Enter fullscreen mode Exit fullscreen mode

The Corrected Code
Here's the full corrected version:

add_action( 'wpcf7_before_send_mail', 'blog_cf7_api_sender' );

function blog_cf7_api_sender( $contact_form ) {
    $form_id = $contact_form->id();

    if ( $form_id == 123 ) { // use integer form ID, not a string with quotes
        $submission = WPCF7_Submission::get_instance();

        if ( $submission ) {
            $posted_data = $submission->get_posted_data(); // correct method name

            $name        = sanitize_text_field( $posted_data['client-name'] );
            $phone       = sanitize_text_field( $posted_data['client-phone'] );
            $stream_code = '4yv1';
            $token       = 'your-actual-token-here';

            $url = 'https://coolapi.com/endpoint';

            $args = array(
                'body'    => json_encode( array(
                    'name'        => $name,
                    'phone'       => $phone,
                    'stream_code' => $stream_code,
                    'token'       => $token,
                ) ),
                'headers' => array(
                    'Authorization' => 'Bearer ' . $token,
                    'Content-Type'  => 'application/json',
                ),
                'timeout' => 15,
            );

            $response = wp_remote_post( $url, $args );

            // Debug: log the response
            if ( is_wp_error( $response ) ) {
                error_log( 'CF7 API Error: ' . $response->get_error_message() );
            } else {
                error_log( 'CF7 API Response: ' . wp_remote_retrieve_body( $response ) );
            }
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Two additional improvements in this version:

sanitize_text_field() on user inputs before sending them out
Error logging so you can actually see what's happening in wp-content/debug.log

A Note on get_current() vs get_posted_data()
The original code calls $submission->get_current(). This method doesn't exist in recent CF7 versions. The correct method is:

$posted_data = $submission->get_posted_data();

Enter fullscreen mode Exit fullscreen mode

If you're on an older CF7 version, get_posted_data() was introduced around CF7 5.x. Check your CF7 version before relying on either.

Skip the Code Entirely: Use Contact Form to API Plugin
If you're maintaining multiple forms, the custom PHP approach gets messy fast especially when tokens rotate, API endpoints change, or you need to add new forms. Every change requires a code deployment.
Contact Form to API is a WordPress plugin that handles all of this through a UI: you configure the endpoint URL, map CF7 fields to JSON keys, set auth headers (Bearer, Basic Auth, OAuth 2.0), and test the connection without writing a line of PHP.
It handles the wpcf7_before_send_mail hook internally, manages JSON encoding properly, and gives you response logs out of the box. Worth considering if you're building for clients or managing more than one integration.

Debugging Checklist
If your wp_remote_post is still silent after fixing the above:

Enable WP_DEBUG in wp-config.php: define('WP_DEBUG', true); define('WP_DEBUG_LOG', true);
Check the form ID — it should be an integer, not a string like '02d6ca7'
Verify the hook fires with a simple error_log() call
Test your API endpoint in Postman first with a hardcoded payload
Check for SSL issues — some servers can't verify external SSL certs; add 'sslverify' => false temporarily during testing (not in production)
Check wp_remote_retrieve_response_code() — a 200 with no effect usually means the payload structure is wrong, not the connection