You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Contact Form 7提交后运行PHP代码?是否可行?

在Contact Form 7提交后运行PHP代码的实现方案

完全可行,Contact Form 7(以下简称CF7)提供了专属的钩子函数,能轻松实现表单提交后执行自定义PHP代码的需求。下面是具体的实现步骤和代码示例:

实现步骤

  1. 选择代码存放位置:推荐使用自定义功能插件(避免主题更新导致代码丢失),或者直接编辑当前主题的functions.php文件。
  2. 使用CF7的提交钩子:最常用的是wpcf7_mail_sent钩子(表单提交且邮件发送成功后触发),如果不需要等待邮件发送,也可以用wpcf7_submit钩子。
  3. 整合你的CURL代码:将你的CURL逻辑写入钩子的回调函数中,还可以按需获取表单提交的数据来动态调整请求内容。

完整代码示例

// 注册CF7表单提交后的回调函数
add_action( 'wpcf7_mail_sent', 'cf7_trigger_custom_curl_request' );

function cf7_trigger_custom_curl_request( $contact_form ) {
    // 可选:仅针对特定ID的CF7表单执行(替换为你的表单ID)
    $target_form_id = 123;
    if ( $contact_form->id() !== $target_form_id ) {
        return;
    }

    // 获取表单提交的数据(按需使用)
    $submission = WPCF7_Submission::get_instance();
    if ( $submission ) {
        $posted_data = $submission->get_posted_data();
        // 示例:获取表单中名为"message"的字段值,替换默认文本
        $message_text = isset( $posted_data['message'] ) ? $posted_data['message'] : 'Hi there!';
    } else {
        $message_text = 'Hi there!';
    }

    // 构造请求数据
    $data = array(
        'chatId' => '9011111@c.us',
        'mentions' => array(
            '9011111@c.us'
        ),
        'text' => $message_text,
        'session' => 'default'
    );

    // 方式1:使用file_get_contents发送请求
    $options = array(
        'http' => array(
            'method' => 'POST',
            'header' => "Content-type: application/json\r\n",
            'content' => json_encode($data)
        )
    );
    $context = stream_context_create($options);
    $result = file_get_contents('http://1.1.1.1:3000/api/sendText', false, $context);

    // 方式2:使用CURL扩展发送(更稳定,推荐当file_get_contents受限使用)
    // $ch = curl_init('http://1.1.1.1:3000/api/sendText');
    // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // curl_setopt($ch, CURLOPT_POST, true);
    // curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    // curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    // $result = curl_exec($ch);
    // curl_close($ch);

    // 可选:将请求结果写入日志,方便调试
    // error_log( 'CF7 CURL请求结果: ' . $result );
}

关键注意事项

  • 表单ID替换:在CF7编辑页面的URL中可以找到表单ID(例如wp-admin/admin.php?page=wpcf7&post=123&action=edit中的123),替换代码中的$target_form_id值。
  • 字段名匹配:如果要获取表单字段值,需确保$posted_data['字段名']中的字段名与CF7表单标签的name属性一致(例如[text* your-name]的字段名是your-name)。
  • 服务器权限:确保你的服务器允许file_get_contents或CURL访问外部URL,若遇到权限问题,优先使用CURL方式。
  • 调试建议:启用代码中的error_log语句,可在WordPress的wp-content/debug.log中查看请求结果,帮助排查问题。

内容的提问来源于stack exchange,提问作者Yunus Emre Kula

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 15:40:20